Home > Back-end >  How to set value foreign key of foreign key Laravel
How to set value foreign key of foreign key Laravel

Time:01-23

I have Visit{id, user_id ,visit_date} model with fk user_id in User{user_id, branch_id, name} Model, I want to show in Visit dashboard the branch description when I select User form visit entry

currently im showing branch_id when user is selected from visit entry,

CodePudding user response:

You need to make one to Many relation from visit to user table and user to branch table

ex. of relationship code:

//From Visit to User model
$this->belongsTo(User::class, 'user_id')

//From User to Branch Model
$this-belongsTo(Branch::clas, 'branch_id')

This will allow you to eager load the relationships in you controller like this

Visit::with(['user.branch'])
//Now you will get all visits with neseted users and branch 

I will recommend you to take a look at laravel relationships docs for a better understanding Laravel Relationships with eager loading

CodePudding user response:

For 2 layers (or more) relationships, I recommend you install this package from Staudenmeir https://github.com/staudenmeir/eloquent-has-many-deep

Inside your Visit model, you can add the relationship like this:

public function branches() {
  $query-> hasManyThrough(Branch::class, User::class);
}

And for more information , check LaravelDaily tutorial related to this package https://youtu.be/wgdWokrm3Mw

CodePudding user response:

Your question isn't clear really! However from what I understand from your question you should also have a Branch model and migration.

So, from visit table you will fetch the users by the relation with user in your visit model.

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

Then when you can fetch your user branches from your User model by your users relation with Branch.

public function branch()
{
    return $this->hasMany(Branch::class, 'user_id', 'id');
}

So, you will fetch data like this:

$visit->user->branch->description

You can replace description with any column_name_that_wish_to_fetch.

  • Related