Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent with and find

Why is this not working?

Article::with('category')->find($ids) 

I got a Array to String Conversion Exception.

But if i split the query into 2 parts like this:

$articles = Article::with('category') 

and

$articles = $articles->find($ids) 

I didn't get any exception and the result is right.

like image 735
Marco Avatar asked May 31 '13 18:05

Marco


People also ask

What is find () in Laravel?

As we know, the find () method in Laravel can be used by any user along with an array of primary keys, and it will return a set of matching records from the database. For example, $student = Students::all (); With the help of the above data, we can get the details of all the students.

What is with () in Laravel?

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.

What is BelongsTo in Laravel?

BelongsTo is a inverse of HasOne. We can define the inverse of a hasOne relationship using the belongsTo method. Take simple example with User and Phone models. I'm giving hasOne relation from User to Phone. class User extends Model { /** * Get the phone record associated with the user.

What is first () in Laravel?

The first() method will return only one record, while the get() method will return an array of records that you can loop over. Also, the find() method can be used with an array of primary keys, which will return a collection of matching records.


1 Answers

Just for the posterity... other way you can do this is:

Article::with('category')->whereIn('id', $ids)->get(); 

This should be faster because it's leaving the query to the database manager

like image 144
dani24 Avatar answered Sep 20 '22 00:09

dani24