Support the ongoing development of Laravel.io →
posted 10 years ago
Eloquent
Last updated 2 years ago.
0

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.

Last updated 2 years ago.
0

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.

Last updated 2 years ago.
0
Solution

Lets see if I can get this : ###User

  • A user can send MANY invitations.
  • A user can receive MANY invitations.

###Invitation

  • An invitation is sent to ONLY ONE user.
  • An invitation is sent by ONLY ONE user.

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

Last updated 2 years ago.
0

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();
Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

meneman meneman Joined 7 May 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.