Let's say I'm having the following database schema:
dogs
and owners
are connected with classic belongsToMany
. How about the walks
table? I'd like to be able to use Eloquent goodies in such kind of relationship:
$dogs = Dog::with('walks')->get();
$walks = Walk::with('dogs')->get();
In theory, I could replace dog_owner_id
with two separate columns: dog_id
and owner_id
. That would make it easy to use Eloquent, but I'd lose some data integrity, because unrelated Dog and Owner could potentially go for a walk (and that's not safe for neither!).
In Walk.php, how should the relations be defined?
public function dog() {
// return ???;
}
How about Dog.php and Owner.php?
public function walks() {
// return ???;
}
Laravel's naming convention for pivot tables is snake_cased model names in alphabetical order separated by an underscore. So, if one model is Feature , and the other model is Product , the pivot table will be feature_product .
To create a pivot table we can create a simple migration with artisan make:migration or use Jeffrey Way's package Laravel 5 Generators Extended where we have a command artisan make:migration:pivot.
The pivot table in laravel is a structured value that is grouped and aggregated in the individual items where the extensive table is obtained or accessed in the form of a spreadsheet, database, or other discrete functions.
1- create 4 Models (Walk,Dog,Owner,DogOwner)
2- in Walk.php model
public function dog()
{
return $this->hasOneThrough(
'App\Models\Dog',
'App\Models\DogOwner',
'id', // Local key on dog_owner table...
'id', // Local key on dogs table...
'dog_owner_id', // Foreign key on walks table...
'dog_id' // Foreign key on dog_owner table...
);
}
public function owner()
{
return $this->hasOneThrough(
'App\Models\Owner',
'App\Models\DogOwner',
'id', // Local key on dog_owner table...
'id', // Local key on owners table...
'dog_owner_id', // Foreign key on walks table...
'owner_id' // Foreign key on dog_owner table...
);
}
3- in Dog.php model
public function walks()
{
return $this->hasManyThrough(
'App\Models\Walk',
'App\Models\DogOwner',
'dog_id', // Foreign key on dog_owner table...
'dog_owner_id', // Foreign key on walks table...
'id', // Local key on dogs table...
'id' // Local key on dog_owner table...
);
}
4- in Owner.php model
public function walks()
{
return $this->hasManyThrough(
'App\Models\Walk',
'App\Models\DogOwner',
'owner_id', // Foreign key on dog_owner table...
'dog_owner_id', // Foreign key on walks table...
'id', // Local key on owners table...
'id' // Local key on dog_owner table...
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With