Laravel - ORM Eloquent with multiple tables

Submitted by sanjok1988 - 4 years ago

if you want to use ORM eloquent to get a query with the third table and select only particular attributes then here is the trick. Here users can have multiple positions in a company and each user has their own user profile. *note that user_id must be here to fetch data with a specific column. without foreign key eloquent cannot map relational table

$user = User::select("id", "name")
        ->with(['positions' => function ($query) {
            $query->select('name');
        }, 'profile' => function ($query) {
            $query->select("user_id", "company_name"); 
        }])->get();


In User model write many to many relation with user positions (designation)

public function positions()
{
    return $this->belongsToMany(\App\Position::class, 'user_position', 'user_id', 'position_id')
    ->withPivot(['position_id', 'user_id']); //if you don't need pivot you can remove it
}

In user Model relation with profile table
public function profile()
{
    return $this->hasOne(Profile::class, 'user_id', 'id');
}