简体   繁体   中英

How can i get First table records on base of third table by using laravel 5 eloquent model

Requested tables are listed below:

**User Table**
id, name
1, vehicle person name
2, renter person name

**Vehicle Table**
id, user_id, vehicle_name
1, 1, My car

**Booking Table**
id, renter_id, vehicle_id
1, 2, 1

User Model

public function renter() {
    return $this->hasMany(Booking::class, 'renter_id');
}

public function vehicleBook() {
    return $this->hasManyThrough(Booking::class, Vehicle::class);
}

Booking Model

public function user() {
        return $this->belongsTo(User::class, 'renter_id');
 }

Vehicle Model

public function user() {
        return $this->belongsTo(User::class);
    }

My Controller

$renters = Auth::user()->renter()->get();
$owners = Auth::user()->vehicleBook()->get();

// In Loop
$renter->user->name; // renter person name
$owner->user->name; // vehicle person name

Result

On base of booking Table i want to get renter person and vehicle person name using Laravel 5 ORM.

I have done that using two calls but i want to know if there is any way to get result using one call ?

You could do something like this. It will reduce the number of lines, but will increase the number of queries.

$user = User::find(Auth::user()->id)->with('renters')->with('vehicleBooks')->first();

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