简体   繁体   中英

Laravel Eloquent Foreign Key Relation

I have question about Laravel Eloquent. I created few tables and models, ~like this:

Trip

  • id
  • name
  • user

User

  • id
  • email

Message

  • id
  • content
  • trip
  • user

How can I get all message for single user with all foreign keys? You know, all data from this tables. Like this:

[
    1 => [
        'content',
        'trip' => [
            'name'
        ],
        'user' => [
            'email'
        ]
    ]
]

It's possible, to get in easy way all data?

My models:

// Message.php:

public function user()
{
    return $this->belongsTo('App\User');
}

public function trip()
{
    return $this->belongsTo('App\Trip');
}

// Trip.php:

public function user()
{
    return $this->belongsTo('App\User');
}

// User.php:

public function trips()
{
    return $this->hasMany('App\Trip');
}

public function messages()
{
    return $this->hasMany('App\Message');
}

My Code

dd(
    User::with([
        'sent',
        'recipient'
    ])->find(2)->toArray()
);

And what I want to get:

screen

I believe you are looking for the load method.

Lets say you have a user

$user->load('messages'); // var_dump($user);

If you vardump your user object you will see the related messages were loaded.

Use eager loading to achieve that.
Try this:

$users = User::with([
        'messages.trip',
    ])->get();

dd($users);

Ref: https://laravel.com/docs/5.3/eloquent-relationships#eager-loading

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM