lundi 2 octobre 2017

Belongs to pivot table in Laravel 5

Let's say I'm having the following database schema:

enter image description here

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 ???;
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire