从内部调用模型


Call model from within itself

我在laravel中有一个模型,需要在其内部调用它来检查是否已经有条目。这是针对一个通用(多态)的情况,我不想在控制器中这样做。

这很好:

$check = self
    ::where('foreign_id',$this->attributes['foreign_id'])
    ->where('foreign_type', $this->attributes['foreign_type'])
    ->where('category', $this->attributes['category'])
    ->orderBy('created_at','desc')
    ->first()
;

现在我可以使用$check->id访问属性了。

但我不能这样做:

$check = self
    ::where('foreign_id',$this->attributes['foreign_id'])
    ->where('foreign_type', $this->attributes['foreign_type'])
    ->where('category', $this->attributes['category'])
    ->orderBy('created_at','desc')
;
if($this->isUser()) $check->where('user_id',$this->attributes['user_id']);
else $check->where('guest_ip',$this->attributes['guest_ip']);
$check->first();

它不是将if语句中的新where添加到查询中。

根据这个答案,我认为自我是一条路:https://stackoverflow.com/a/15282754/1233206

然而,就我而言,它似乎不起作用。我做错了什么?

$check->first()将运行查询并返回结果。$check变量本身不会更改。所以如果你尝试这个:

$check->first();
if($check->id == 'something'){}

它不起作用,因为您正在与查询生成器实例交互。你必须这样做:

$check = $check->first();
if($check->id == 'something'){}