从Laravel中的hasMany关系返回第一个模型 [英] Returning the first model from a hasMany relationship in Laravel

查看:539
本文介绍了从Laravel中的hasMany关系返回第一个模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以创建一种快速的方法来从一对多关系中返回第一个模型?这是我的代码,来自模型文件:

Is it possible to create a quick method to return the first model from a one-to-many relationship? Here is my code, from the model file:

public function books() {
    return $this->hasMany('App\Models\Book');
}

public function first_book() {
    return $this->book()->first();
}

这是我得到的错误:

'Call to undefined method Illuminate\Database\Query\Builder::addEagerConstraints()'

我要使用它的原因是为了可以使用with()方法收集第一条记录,例如:

The reason I want to use this is so that I can collect the first record using the with() method, for example:

    $authors = Author::with('first_book')->select('*');

我正在将这些记录与数据表一起使用.

I'm using these records with Datatables.

推荐答案

我可能来晚了,但是为了您将来使用以及其他想要相同输出的人,请尝试使用此方法-

I might be late but for your future use and for other who want the same output try this one -

//如果需要最后一个

public function books() {
    return $this->hasOne('App\Models\Book')->latest();
}

//如果需要第一个条目-

// If you need the first entry -

public function books() {
        return $this->hasOne('App\Models\Book')->oldest();
    }

这篇关于从Laravel中的hasMany关系返回第一个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆