简体   繁体   English

Eloquent OrderBy 和 Take 在 hasMany 关系中不起作用

[英]Eloquent OrderBy and Take not working in a hasMany relationship

I am trying to limit the number of entries returned in a hasMany relationship which works fine when either orderBy or take is used.我试图限制在 hasMany 关系中返回的条目数,这在使用 orderBy 或 take 时工作正常。 However when they are used together, the results appear to be wrong.但是,当它们一起使用时,结果似乎是错误的。

What is wrong with this query?这个查询有什么问题?

Expected Results = 2 rows of data预期结果 = 2 行数据

Actual results = 2 rows of data实际结果 = 2 行数据

public function manual_ticket_log(){
    return $this->hasMany('App\ManualTicketLog','manual_ticket_id','id')->orderBy('id','desc');
}

Expected Results = 1 row of data预期结果 = 1 行数据

Actual Results = 1 row of data实际结果 = 1 行数据

public function manual_ticket_log(){
    return $this->hasMany('App\ManualTicketLog','manual_ticket_id','id')->take(1);
}

--ERROR HERE-- --这里有错误--

Expected Results = 1 row of data预期结果 = 1 行数据

Actual results = Empty array is returned实际结果 = 返回空数组

  public function manual_ticket_log(){
        return $this->hasMany('App\ManualTicketLog','manual_ticket_id','id')->orderBy('id','desc')->take(1);
    }

intead of hasMany you can use HasOne to get only one record: intead hasMany 你可以使用 HasOne 来只获取一条记录:

public function manual_ticket_log(){
        return $this->hasOne('App\ManualTicketLog','manual_ticket_id','id')->orderBy('id','desc');
    }

hasOne will get the first result only. hasOne 只会得到第一个结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM