Understanding Laravel's Eloquent Model

Asked 2 years ago, Updated 2 years ago, 42 views

Let me ask you a rudimentary question about Eloquent.
Get() could not retrieve data from the BelongTo destination table.

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Item extensions Model
{
    public function user(): BelongsTo
    {
        return$this->belongsTo('App\User');
    }
}
$item=Item::where('id',1)->get();

The could not retrieve information about the associated user.

$item=Item::where('id',1)->first();

Then, the user table was joined and user information was retrieved.

With get, can't I get the data only from the table that corresponds to the model?

php laravel

2022-09-30 11:51

1 Answers

There is no concept of join in Eloquent.

The behavior of creating a relationship like belongTo() is usually Lazy Loading, and in this example, the data in the users table is retrieved as follows:

$item=Item::where('id',1)->get();
echo$item[0]->user->name;

// Display the name of the user tied to the item

At this time, Eloquent runs SQL as follows:

select* from items where id=1;
select * from users where id = {items.user_id};

In addition, the recommended method for using with in tech blogs and manuals is as follows:

$item=Item::with('users')->where('id',1)->get();
echo$item[0]->user->name;

// Display the name of the user tied to the item

At this time, Eloquent runs SQL as follows:

select* from items where id=1;
select * from users where id in ({ items.user_id});

Also, if you use the misunderstood first this time, it will be as follows.

$item=Item::where('id',1)->first();
echo$item->user->name;

// Display the name of the user tied to the item
select* from items where id=1 limit1;
select * from users where id = {items.user_id};

The difference is that get() is supposed to return multiple collections of each user in an array, while first() is supposed to return only one collection, so the collection itself is returned.Perhaps you also expected to retrieve the value as $item->user->name when you got(), but it didn't happen, and you might be mistaken that you were joined because you could retrieve it as $item->user->name in fist().


2022-09-30 11:51

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.