Laravel HasMany relation with parameters - laravel

i have a relation between User model and Friend model
User.php
public function friends()
{
return $this->hasMany(Friend::class);
}
the relation actually returns all the records where the foreign key column (user_id) between User and Friend equals the current user's id but i want to return also the records where current user's id is in another column in friends table which's name is friend_id, this is my try
public function friends()
{
return $this->hasMany(Friend::class,'user_id','friend_id');
}
it's actually not returning the correct records

I don't think there is a direct way to that but you could try making 2 relations and merge them into one relation
public function friends() {
return $this->hasMany(Friend::class);
}
public function additionalfriends() {
return $this->hasMany(Friend::class, 'friend_id');
}
public function allfreinds() {
return $this->friends->merge($this->additionalfriends);
}
another solution you might try is
public function friends()
{
return Friend::where(function($query) {
$query->where('user_id',$this->id)
->orWhere('friend_id',$this->id);
});
}

Related

MorphMany to MorphTo relation

I have mangers table and funds table in my laravel project
Managers -> id, name, wallet
Funds -> id, amount, fundable_type, fundable_id, receivable_type, receivable_id, status
I have the following relations in Manager model
public function funds()
{
return $this->morphMany(Fund::class, 'fundable');
}
public function receiveds()
{
return $this->morphMany(Fund::class, 'receivable');
}
I have the following relations in Fund model
public function fundable()
{
return $this->morphTo();
}
public function receivable()
{
return $this->morphTo();
}
$manager->funds is populating fund models well.
I want to receive the managers who received fund a particular manager.
I tried $manager->funds->receivable but it is not working.
In relations specifications you can append the other model's relations:
public function funds()
{
return $this->morphMany(Fund::class, 'fundable')->with('receivable');
}
Okay, I was able to get the answer myself.
public function managers()
{
return $this->hasManyThrough(Manager::class, Fund::class, 'fundable_id', 'id', 'id', 'receivable_id')
->where('fundable_type', Manager::class)->where('receivable_type', Manager::class)->distinct();
}

Laravel One to Many relation with 2 primary keys

I've 2 tables
Users table
id
name
...
Chats table
id
from_id // fk - id on users, the user sent the message
to_id // fk - id on users, intended user
message_body
Now, I'm trying to set up One to Many relation where user has many chat messages but a chat message has two user. from and to user
How can I define this relationship?. I have to user eager loading.
I tried to use Compoships but it didn't work.
My code
User Model
public function chats() {
return $this->hasMany(Chat::class, ['from_id', 'to_id'], 'id');
}
Chat Model
public function user() {
return $this->belongsTo(User::class, ['from_id', 'to_id'], 'id');
}
public function chats() {
return $this->hasMany(Chat::class, 'from_id', 'id') + $this->hasMany(Chat::class,'to_id','id');
}
public function userFrom() {
return $this->belongsTo(User::class, 'from_id', 'id');
}
public function userTo() {
return $this->belongsTo(User::class, 'to_id', 'id');
}
Why don't you do something like that?
On your User model, set up two relationships like this:
public function chatsFrom() {
return $this->hasMany('App\Chat', 'from_id');
}
public function chatsTo() {
return $this->hasMany('App\Chat', 'to_id');
}
Then, on your Chat model, also set up two relationships, one to from and another to to, both referencing a User model. Like this:
public function fromUser() {
return $this->belongsTo('App\User', 'from_id');
}
public function toUser() {
return $this->belongsTo('App\User', 'to_id');
}
This way, you can access the relationships using something like this:
$user->chatsFrom();
$user->chatsTo();
$chat->fromUser();
$chat->toUser();

Laravel how to define 3 relationships with one model?

I have a Model which is called Championship. Championship may have 3 judges which are called Main Judge, Main Secretary and Judge Operator.
All of them linked to User Model and stored in the database as user ID.
My relationships looks like this
class Championship extends Model
{
protected $table = 'championships';
public function mainJudge()
{
return $this->hasOne('App\User', 'id', 'main_judge');
}
public function mainSecretary()
{
return $this->hasOne('App\User', 'id', 'main_secretary');
}
public function judgeOperator()
{
return $this->hasOne('App\User', 'id','judge_operator');
}
}
But I can't undertand how to define inverse relationship in User model
class User extends Authenticatable
{
public function sex()
{
return $this->belongsTo('App\Models\Sex');
}
public function player()
{
return $this->hasOne('App\Models\Player', 'user_id');
}
public function championship()
{
????
}
You just have to add it like you are adding other relations :
public function championship()
{
return $this->belongsTo('App\Championship');
}
When you do :
$championship = Championship::find($id);
$mainJudge = $championship->mainJudge;
$mainSecretary = $championship->mainSecretary;
// All objects will be exactly same
dd($mainJudge->championship,$mainSecretary->championship,$championship);
I assume all the user records have a foreign key to championships table championship_id
When you call the $user->championship relation it will return you the championship wrt to its foreign key championship_id
No need to worry you are just confusing the inverse relations:
See it this way:
Your mainJudge, mainSecretary, judgeOperators are of type App\User and every user have a championship_id when you will call the (App\User)->championship it will always return you its respective championship or null if the championship_id is empty.
Its just matter of perspective.
Just try the above code it will clear out your confusion.

Laravel getting realtionship with auth()

I have the following relationship in User.
public function partner()
{
return $this->hasOne('App\Partner','partner_id');
}
And I am accessing that relationship
auth()->user()->partner()->name
But it gives me exception where name is available in partners table:
Undefined property: Illuminate\Database\Eloquent\Relations\HasOne::$name`
And the user object from auth()->user()->partner() is also empty.
What am I missing?
auth()->user()->partner() returns the relation binding, not the model itself.
try auth()->user()->partner->name instead.
First, ensure you setup the right relationship:
User.php
public function partner()
{
return $this->hasOne('App\Partner');
}
Partner.php
public function user()
{
return $this->belongsTo('App\User');
}
To access the user's partner:
// Get the user's Partner instance:
$partner = auth()->user()->partner;
// Access the user's partner properties:
$partner_name = auth()->user()->partner->name;
Also, check that your partners table has the column user_id.
I think you are doing it wrong, All you have to do is that to change :
public function partner()
{
return $this->hasOne('App\Partner','partner_id');
}
to
public function partner()
{
return $this->belongsTo('App\Partner');
}
A user belongs to a partner, Cause partner is a meta table.

laravel 5 pivot table

I'm trying to implement a friendlist for a user
so a user can have many friends
but for calling the friends I'm having trouble getting my relation right:
user
id
friends
user_id
friend_user_id
Class user:
public function Friends(){
return $this->hasMany('App\User', 'friends');
}
So Auth::User()->Friends should return a list of User models
You actually don't have a "one to many" relationship but rather "many to many" with friends being your joining table
Try this:
public function Friends(){
return $this->belongsToMany('App\User', 'friends', 'user_id', 'friend_user_id');
}
When creating a relation to the same model, you would do something like this:
Models/User.cs
public function Friends()
{
return $this->hasMany('User', 'user_friend_of', 'id'); // assuming user_friend_of is the FK on user-table
}
public function User()
{
return $this->belongsTo('User');
}
This would mean you have only 1 table, which has a foreign key to another row in the same table, for instance: (id - name - user_friend_of )
In your user class, define the function as follows:
public function Friends(){
return $this->hasMany('friends');
}
Calling $user->Friends()->get() should return you everything you need. Note that 'friends' should be the name of the table.

Resources