0

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

是否可以使用“with”来完成,还是只能使用“Joins”?

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

4

2 回答 2

0

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

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

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

于 2021-05-05T13:36:20.130 回答
0

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

$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 建立的约定。我把相关链接留在这里,我相信它们会很有帮助。问候。

关系:一对一

关系:单程

于 2021-05-05T14:05:47.460 回答