2016-07-05 76 views
1

我已经阅读了Laravel 5.1的文档,但是我找不到(或理解)一种让父母的ID有孩子的方法。我可以与查询生成器是这样做的:如何在Laravel找到一个父母身份的孩子?

$child = \DB::table('children_table')->where('parent_id', $parent->id)->first(); 

但随着该问题是,它返回一个stdClass的,这是我以后不能再使用更新属于关联关系。 任何人都可以帮忙吗?

+0

'child'通常与'parents'有'hasMany'关系吗?如果是这样,请调用关系,并且如果你想要一个*特定的*父项,则合并一个where。 '$ child-> parent() - > find($ parent-> id);',假设关系名称相当标准。 – CmdrSharp

+0

虽然看起来你并不想在你的例子中得到一个'child'。因为您正在从'parents_table'中获取记录。 – Doom5

+0

对不起,我的意思是'children_table',我现在就编辑它。 –

回答

0

不知道这是你在说什么,但你可以试试这个:

在父类:

class Parent extends Model 
{ 
    public function children() 
    { 
     return $this->hasMany('App\Child'); 
    } 

在孩子类:

class Child extends Model 
{ 
    public function parent() 
    { 
     return $this->belongsTo('App\Parent'); 
    } 

然后,你应该可以做一些事情:

App\Parent::with('children')->find($id); 
0

您可以在雄辩的模型中使用查询生成器方法,如where

由于口才型号查询生成器,你应该检查所有的 方法上查询生成器可用。您可以在您的Eloquent查询中使用这些 方法中的任何一种。

https://laravel.com/docs/5.2/eloquent#retrieving-multiple-models

看到标题为添加附加约束

相关问题