Try to use one relationship M:M and two tables
Users [user_id, username, firstname, lastname,...]
Invitations[invitation_id, caller_user_id, called_user_id]
The caller_user_id could be an user id and the called_user_id could be another user id referencing the same users table.
One user can call one or more users and a user could be called for one or more users.
You can call it invitations, friends, etc.
What you said there is exactly what i have on my picture actually. Two tables, one with the Users and one with the Invitations, where to columns are users_ids. I want to know how i set this up in laravel using Eloquent.
Lets see if I can get this : ###User
###Invitation
Invitations Table Schema : id (increments), sender_id (integer), receiver_id (integer)
...
/**
* Query the invitations sent BY this user.
*
* @return Illuminate\Database\Eloquent\Relations\HasMany
*/
public function invitationsSent()
{
return $this->hasMany('Invitation', 'sender_id');
}
/**
* Query the invitations sent TO this user.
*
* @return Illuminate\Database\Eloquent\Relations\HasMany
*/
public function invitationsReceived()
{
return $this->hasMany('Invitation', 'receiver_id');
}
File : ../models/User.php
...
/**
* Query the user this invitations was sent BY.
* (Sender of this invitation)
*
* @return Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function sender()
{
$this->belongsTo('User', 'sender_id');
}
/**
* Query the user this invitations was sent TO.
* (Receiver of invitation)
*
* @return Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function receiver()
{
$this->belongsTo('User', 'receiver_id');
}
File : ../models/Invitation.php
meneman said: What i want to do is someting like this: $invites = Invite::to_user(2); $invites->count(); for example.
Alternatively you can do it this way :
$invitesToUser = User::find(2)->invitationsReceived()->count();
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community