微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Laravel:With 和 whereHas 过滤第二个关系 hasOne

如何解决Laravel:With 和 whereHas 过滤第二个关系 hasOne

我正在尝试使用关系的“with”和“whereHas”过滤表,并使其遵循第二个关系。

是否可以使用“with”来实现,或者只能使用“Joins”来实现?

Ticket >> StatusHistory(最后一条记录)>> StatusName = 'new'

ticket
    -id 
    -name

status_history
    - ticket_id
    - status_name_id
    - timestamps

status_names
    - id
    - name  (new,close,paused)
<?

class Ticket extends Model
{

    public function latestStatus()
        {
            return $this->hasOne(StatusHistory::class,'ticket_id','id')->latest();
        }




class StatusHistory extends Model
{
    public function statusName()
    {
        return $this->hasOne(StatusName::class,'id','status_name_id');
    }

This usually works well if there is only one Status history record,but if there are more,it returns values that should not be there.

example:  ticket_id 1 has in history first status new and them status paused 

With this sentence he returned the ticket to me even so he no longer has the last status in "new".
    Ticket::with('latestStatus')
            ->whereHas('latestStatus.statusName',function($q){
                $q->where('name','new');
            })

解决方法

根据文档 (https://laravel.com/docs/8.x/eloquent-relationships#constraining-eager-loads) 是可能的。它看起来像这样:

    Ticket::with(['latestStatus' => function($q){
          $q->where('name','new');
    }])->get();

以便子查询链接到您尝试加载的关系

,

要访问您刚刚使用的第一个关系:

$ticket = Ticket::find($id);
$ticket->latestStatus

通过建立“hasOne”关系,这将返回相关记录,从我看到的也有一个hasOne关系,因此您可以执行以下操作:

$ticket->latestStatus->statusName

通过这种方式,您正在访问第二个关系并照常工作。

然而,这不是唯一的方法,因为 Laravel 还通过“has-one-through”方法提供对链式关系的访问,根据文档定义为:

“...这种关系表明声明模型可以通过第三个模型与另一个模型的一个实例进行匹配。”​​

class Ticket extends Model{
    public function statusName()
    {
        return $this->hasOneThrough(StatusName::class,StatusHistory::class);
    }
}

请注意,为此您必须遵循 Laravel 建立的约定。我把相关链接留在这里,我相信它们会很有帮助。问候。

Relationships: one-to-one

Relationships: has-one-through

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。