现在我有3个表
衬衫id type
颜色id color
color_shirt
id color_id shirt_id
衬衫模型
public function colors()
{
return $this->belongsToMany('Color');
}
衬衫控制器
public function show($color)
{
$color = Shirt::find('round_collar')->color();
}
它将返回圆领衬衫的所有颜色,如果我想返回特定的颜色该怎么办?
它不能以以下方式工作:
$color = Shirt::find('round_collar')->colors()->where('color','=','red');
当我参考文档http://four.laravel.com/docs/eloquent#many-to-many时,它似乎没有示例。有人知道答案吗?
尝试在末尾添加->get()或->first(),如下所示:
$color = Shirt::find('round_collar')->color()->where('color','=','red')->get();
你可以使用'Eager Loading Constraints' (http://laravel.com/docs/eloquent#eager-loading)
Shirt::find('round_collar')->with(array('colors' => function($query) {
$query->where('color', '=', 'red');
}))->first();
作为旁注,我怀疑您想以这种方式使用find('round_collar')。你可能想要where('collar', '=', 'round')。