I can't seem to be able to get my pivot relationships when using a belongs to many relationship! My structure looks like this
user Model
class Users extends Model
{
protected $table = 'users';
public function contacts(){
return $this->belongsToMany('App\Models\Contacts', 'user_contacts', 'user_id', 'contact_id');
}
}
contacts Model
class Contacts extends Model
{
protected $table = 'contacts';
}
user_contacts Table
id | user_id | contact_id
1 | 1 | 1
users Table
id | Name
1 | Jim Bliggs
contacts Table
id | Name | Telephone
1 | Joe Bloggs | 0 111 1111
I can save using the relationship fine like so
$user->contacts()->save($newContact);
But whenever I try to get all the contacts for a user to loop through them like this
$users = Users::all();
dd($users->contacts);
It just returns
Property [Contacts] does not exist on this collection instance.
Sorry if its a simple question, but I cant understand how I can create using the relationship but i cant read?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire