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

时间:2014-04-08 18:09:12

标签: php laravel-4 eloquent

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

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');
    }
}

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

$mealProp = Meal::first()->mealProperties->first();

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

$mealProp = Meal::first()->mealProperties->where('id','=','1')->first();

我收到此错误:

Call to undefined method Illuminate\Database\Eloquent\Collection::where()

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

如果我不能使用哪种方法,有什么方法可以获得特定的膳食属性?

谢谢你的帮助!

2 个答案:

答案 0 :(得分: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();

你必须区分Laravel行为:

(动态属性)Eloquent Collection或Model

$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();

答案 1 :(得分:1)

你可以试试这个:

$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();