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(); }
This is the error I'm getting:
Call to undefined method Illuminate\Database\Query\Builder::addEagerConstraints()
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 don't know what version of Laravel you were using, but first() doesn't throw an exception if the table doesn't have matching rows, and I know it hasn't since at least Laravel 4.2. It just returns null. It may be that the exception was caused by a different issue with your code.
with() function is used to eager load in Laravel. Unless of using 2 or more separate queries to fetch data from the database , we can use it with() method after the first command. It provides a better user experience as we do not have to wait for a longer period of time in fetching data from the database.
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('App\Models\Book')->latest(); }
// If you need the first entry -
public function books() { return $this->hasOne('App\Models\Book')->oldest(); }
A relation that can be eager loaded has to return a query. The first()
function returns an eloquent object.
The solution is to limit the number of results of this query like so:
public function first_book() { return $this->books()->take(1); }
$author->first_book
will still be a collection, but it will only contain the first related book in your database.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With