Laravel-eloquent:调用未定义的方法Illuminate\Database\Eloquent\Collection :: where()

Mar*_*lek 5 php eloquent laravel-4

我有两种模式,多对一关系:

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');
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我要求第一餐第一餐属性一切顺利:

$mealProp = Meal::first()->mealProperties->first();
Run Code Online (Sandbox Code Playgroud)

但是,如果我用这种方式询问具有第一餐特定id的mealProperty:

$mealProp = Meal::first()->mealProperties->where('id','=','1')->first();
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

Call to undefined method Illuminate\Database\Eloquent\Collection::where()
Run Code Online (Sandbox Code Playgroud)

我两个小时谷歌我做错了什么,但仍然没有.

如果我不能使用where where方法,有什么方法可以获得特定的mealProperty?

谢谢你的帮助!

Jar*_*zyk 10

Laravel 5的更新:

自v5发布以来where,Support\Collection对象上有一个方法,所以这个问题/答案变得无关紧要.该方法完全相同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();
Run Code Online (Sandbox Code Playgroud)

你必须区分Laravel的行为:

(动态属性)Eloquent Collection或Model

$meal->mealProperties
Run Code Online (Sandbox Code Playgroud)

关系对象

$meal->mealProperties()
Run Code Online (Sandbox Code Playgroud)

现在:

// 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();
Run Code Online (Sandbox Code Playgroud)