无法使用 hasManyThrough 方法检索远程数据
can't retrieve distant data with hasManyThrough method
为了举例,我有这个设置:
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('App\Post', 'App\Collected_item');
}
但是我该如何检索这些帖子?由于我正在按名称寻找模型,因此我尝试这样无济于事:
$posts = Item_model::where('model_name', 'LIKE', $q . '%')->posts();
或
$posts = Item_model::where('model_name', 'LIKE', $q . '%')->posts()->get();
返回错误:
调用未定义的方法 Illuminate\Database\Query\Builder::posts()
尝试"with"方法..
$posts = Item_model::with('posts')->where('model_name', 'LIKE', $q . '%')->get();
要仅获取帖子所在的 item_models,请使用 "has" 方法
$posts = Item_model::has('posts')->where('model_name', 'LIKE', $q . '%')->get();
我认为你必须在进行 get 调用之前声明方法的名称
Item_model::with('posts')->get();
我终于让它工作了。这是 Item_model
中的正确关系
public function posts()
{
return $this->hasManyThrough('App\Post', 'App\Collected_item', 'model_id', 'collected_item_id', 'id' );
}
其中第三个参数是中间模型中的外键,第四个是 Post 模型上的外键,第五个是本地 (item_model) 键。
之后,无需抢先加载帖子,我可以这样做:
$item= Item_model::find(220); (an item which I know has related posts)
$posts = $item->posts;
dd($posts);
这个 returns 帖子,所以你必须像其他人建议的那样先加载它们是不正确的,hasManyThrough 方法负责检索帖子。
为了举例,我有这个设置:
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('App\Post', 'App\Collected_item');
}
但是我该如何检索这些帖子?由于我正在按名称寻找模型,因此我尝试这样无济于事:
$posts = Item_model::where('model_name', 'LIKE', $q . '%')->posts();
或
$posts = Item_model::where('model_name', 'LIKE', $q . '%')->posts()->get();
返回错误:
调用未定义的方法 Illuminate\Database\Query\Builder::posts()
尝试"with"方法..
$posts = Item_model::with('posts')->where('model_name', 'LIKE', $q . '%')->get();
要仅获取帖子所在的 item_models,请使用 "has" 方法
$posts = Item_model::has('posts')->where('model_name', 'LIKE', $q . '%')->get();
我认为你必须在进行 get 调用之前声明方法的名称
Item_model::with('posts')->get();
我终于让它工作了。这是 Item_model
中的正确关系public function posts()
{
return $this->hasManyThrough('App\Post', 'App\Collected_item', 'model_id', 'collected_item_id', 'id' );
}
其中第三个参数是中间模型中的外键,第四个是 Post 模型上的外键,第五个是本地 (item_model) 键。
之后,无需抢先加载帖子,我可以这样做:
$item= Item_model::find(220); (an item which I know has related posts)
$posts = $item->posts;
dd($posts);
这个 returns 帖子,所以你必须像其他人建议的那样先加载它们是不正确的,hasManyThrough 方法负责检索帖子。