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

查看:20
本文介绍了从 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('AppModelsBook');
}

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

这是我得到的错误:

Call to undefined method IlluminateDatabaseQueryBuilder::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 -

//如果你需要最后一个

// If you need the last one

public function books() {
    return $this->hasOne('AppModelsBook')->latest();
}

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

// If you need the first entry -

public function books() {
        return $this->hasOne('AppModelsBook')->oldest();
    }

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

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