Mattaton
Mattaton

Reputation: 247

Complex relationships with Laravel/Eloquent

I'm just getting into Laravel (5.3) and have been running over Eloquent scenarios in my head trying to figure out how I'd accomplish more complex relationships between models/tables.

In my example here, I'm building a contacts app. Users have many contacts, that's easy. The trickier part is defining contact connections. Say a user has two contacts that are sisters. The user can connect these two contacts to easily move between them. The user can assign an unlimited amount of connections to a contact.

So, I obviously have a users table with an id and a contacts table with id and a user_id field to attach it to a user. The user can also create multiple connection names. Like, "sister." Once the user creates a new connection name, I want to store it so they can easily use the same connection name later with a type-ahead input or something. So, the connection_names table has entries tied to a user.

The table I'm having a hard time with is the actual connections pivot table. I assume it's a pivot table anyway. Still kinda new to all the terminology. The diagram kinda says it all. The connections table is basically all ids connecting to other tables. Two ids from the contacts table establishing the connection itself, and one more id for the name of the connection.

So, first, how in the world do I setup the models to define the connections relationships in Laravel with eloquent? And is there something I could/should do better or more cleanly? Also, am I doing the naming conventions correctly for Laravel/Eloquent to automatically pick any or all of this up?

Thanks so much! connections diagram

Upvotes: 0

Views: 531

Answers (1)

Amit Gupta
Amit Gupta

Reputation: 17658

If you have a $connection object and want access the Contact object (host or connected user) then you can use belongsTo as:

public function host()
{
    return $this->belongsTo('App\Contact', 'contact_id');
}

public function connection()
{
    return $this->belongsTo('App\Contact', 'connection_id');
}

And if you have an object of Contact model and want to access all connection then you need a belongsToMany relation as:

public function connection()
{
    return $this->belongsToMany('App\Contact', 'connections', 'contact_id', 'connection_id');
}

Your naming conventions are done correctly.

Upvotes: 1

Related Questions