我有两个多对一关系的模型:
class Meal extends \Eloquent {
/**
* public Integer $id; - primary key
* public String $name;
*/
protected $fillable = array('id','name');
public function mealProperties()
{
return $this->hasMany('MealProperty');
}
}
class MealProperty extends \Eloquent {
/**
* public Integer $id; - primary key
* public Integer $meal_id;
*/
protected $fillable = array('id','meal_id');
public function meal()
{
return $this->belongsTo('Meal', 'meal_id');
}
}如果我先要第一顿饭,mealProperty,一切都很好:
$mealProp = Meal::first()->mealProperties->first();但是如果我以这种方式请求带有第一顿饭的特定id的mealProperty:
$mealProp = Meal::first()->mealProperties->where('id','=','1')->first();我得到了这个错误:
Call to undefined method Illuminate\Database\Eloquent\Collection::where()我在谷歌上搜索了两个小时我做错了什么,但仍然一无所获。
如果我不能使用where方法,有什么可能的方法来获取特定的mealProperty?
感谢您的帮助!
发布于 2014-04-09 02:25:19
Laravel 5的更新:
自v5发布以来,Support\Collection对象上有一个方法where,因此这个问题/答案变得无关紧要。该方法的工作原理与filter完全相同,即。直接返回过滤后的集合:
$mealProp = Meal::first()->mealProperties->where('id','=','1'); // filtered collection
// that said, this piece of code is perfectly valid in L5:
$mealProp = Meal::first()->mealProperties->where('id','=','1')->first();您必须区分Laravel行为:
(动态属性)雄辩的集合或模型
$meal->mealProperties关系对象
$meal->mealProperties()现在:
// mealProperties is Eloquent Collection and you call first on the Collection here
// so basically it does not affect db query
$mealProp = Meal::first()->mealProperties->first();
// here you try to add WHERE clause while the db query is already called
$mealProp = Meal::first()->mealProperties->where('id','=','1')->first();
// So this is what you want to do:
$mealProp = Meal::first()->mealProperties()->where('id','=','1')->first();发布于 2014-04-09 02:54:55
你可以试试这个:
$mealProop1 = Meal::first()->mealProperties->find(1); // id = 1或者类似这样的东西:
$mealProops = Meal::first()->mealProperties;
$mealProop5 = $mealProops->find(5); // id = 5
$mealProop7 = $mealProops->find(7); // id = 7而不是这样:
$mealProp = Meal::first()->mealProperties->where('id','=','1')->first();另外,下面的代码应该可以工作:
$mealProp = Meal::first()->mealProperties->first();https://stackoverflow.com/questions/22944937
复制相似问题