Laravel-eloquent: 找不到 Illuminate\Database\Eloquent\Collection::where() 方法

9

我有两个模型处于多对一关系:

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

如果我请求第一餐并且传递了first mealProperty参数,那么一切都会正常执行:

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

但是如果我用特定的第一餐id询问mealProperty,应该怎么做呢?
$mealProp = Meal::first()->mealProperties->where('id','=','1')->first();

I get this error:

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

我花了两个小时谷歌搜索,但仍然找不到我做错了什么。
如果不能使用where方法,有什么其他的方法可以获取特定的mealProperty?
感谢您的帮助!
2个回答

13

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 的行为:

(动态属性) 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();

是的,它完美地运行了!谢谢你的解释!:) - Martin Filek
$mealProp = Meal::first()->mealProperties->first(); 这样写没问题。 - The Alpha
是的,它会,就像我说的那样,它被称为在集合上而不是在数据库查询中。 - Jarek Tkaczyk
哇,这是一个很重要的知识点。现在看起来很明显,但我刚开始真的没有发现问题出在哪里。方法与属性同名的问题。 - MHG

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

谢谢你的回答!你是正确的,对于id属性来说这是更好的方法。 - Martin Filek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接