为了示例,我有此设置:
item_model
id - integer
name - string
collected_item
id - integer
model_id - integer
posts
id - integer
collected_item_id - integer
title - string
我想通过collected_item型号检索有关item_model的所有帖子。
所以我在item_model中设置了关系:
public function posts()
{
return $this->hasManyThrough('AppPost', 'AppCollected_item');
}
但是如何检索帖子?由于我正在寻找名字的模型,因此我尝试过这样的方法:
$posts = Item_model::where('model_name', 'LIKE', $q . '%')->posts();
或
$posts = Item_model::where('model_name', 'LIKE', $q . '%')->posts()->get();
返回错误:
致电到未定义的方法照明 database query builder :: posts()
尝试"用"方法。
$posts = Item_model::with('posts')->where('model_name', 'LIKE', $q . '%')->get();
仅获取存在帖子存在的item_models使用"有"方法
$posts = Item_model::has('posts')->where('model_name', 'LIKE', $q . '%')->get();
我终于使它起作用。这是item_model中的正确关系
public function posts()
{
return $this->hasManyThrough('AppPost', 'AppCollected_item', 'model_id', 'collected_item_id', 'id' );
}
,第三个参数是中间模型中的外键,第四个邮政模型上的外键,第五个是本地(item_model)键。
之后,不必先进行帖子,我可以做:
$item= Item_model::find(220); (an item which I know has related posts)
$posts = $item->posts;
dd($posts);
这将返回帖子,因此您必须像其他建议一样,在其他建议的情况下加载它们,而HasmanyThrough方法负责检索帖子。
我认为您必须在呼叫之前声明该方法的名称
item_model :: with('ports') -> get();