Daniel-Pablo's avatar

Better way to get this query :) HELP

Hi, community please, I am writing my code got this

$user->connections; // user have connections and get this

[
{
id: 2,
name: "pepote",
email: "[email protected]",
email_verified_at: null,
created_at: "2020-04-13T02:21:46.000000Z",
updated_at: "2020-04-13T02:21:46.000000Z",
pivot: {
user_id: 1,
connect_id: 2,
show: 1,
chat_room: "1GFwjj92",
created_at: "2020-04-14T17:19:06.000000Z",
updated_at: "2020-04-14T17:19:06.000000Z"
}
}
]

so yes the user has at this moment ONE connection, if I want to just get the chat room I have to write this code:

return $myConnections->first()->pivot->chat_room;

I don't want to mention the PIVOT it's there another way to call this???? Thanks a lot in advance, got a better answer!

0 likes
7 replies
frankincredible's avatar

I'm not sure what you're asking.

You can add withPivot('chat_room') to the original query to have it included with the connections.

Daniel-Pablo's avatar

thanks @frankincredible I did this way

  public function connections()
  {
    return $this->belongsToMany('App\User' , 'user_user' , 'user_id' , 'connect_id' )->withPivot('show', 'chat_room')->withTimestamps();
}

okay I am asking if there is other way to call the pivot table... just if there exist the way if not I will leave it that way

frankincredible's avatar
Level 14

Alternatively you can make a Model for the actual pivot itself, and write a relation that just returns the pivot. It's up to you.

PovilasKorop's avatar

From the official docs:

you may wish to rename your intermediate table accessor to subscription instead of pivot. This can be done using the as method when defining the relationship:

return $this->belongsToMany('App\Podcast')
                ->as('subscription')
                ->withTimestamps();

Once this is done, you may access the intermediate table data using the customized name:

$users = User::with('podcasts')->get();

foreach ($users->flatMap->podcasts as $podcast) {
    echo $podcast->subscription->created_at;
}
1 like
Daniel-Pablo's avatar

thanks I made this - thing is the best way to get the chat_room table

public function chatRooms()
{
    return $this->hasMany( 'App\ChatRooms' , 'user_id');
}

Please or to participate in this conversation.