Laravel: How to get a single summary string by key id

I have a many-to-many relationship established on User and Notification models. This way I can access the pivot table - user_notifications - as follows:

$user = User::find(1); foreach ($user->notifications() as $n) { echo $n->pivot->created_at; } 

This will give me all the values โ€‹โ€‹of the created_at field from the pivot table, for user ID = 1.

What if I need only one summary line, say with notification_id = 2 ? Is there a way to combine pivot with where or has ? Can this be done without scrolling through $user->notifications() ?

+5
source share
3 answers

You can use the where clause with respect to:

 $notification = $user->notifications()->where('notification_id', 2)->first(); echo $notification->pivot->created_at; 
+5
source

You can also use the find method directly.

 $notification = $user->notifications()->find(2); echo $notification->pivot->created_at; 
+3
source

I dealt with this, and the answer to lukasgeiter is fine, until the strange case where you want to find the id summary string (if you set the column $table->increments('id') to ( Define custom staging table models @ https: / /laravel.com/docs/5.6/eloquent-relationships )

What you can do in this strange case:

 $notification = $user->notifications()->having('pivot_id', 2)->first(); echo $notification->pivot->created_at; 

You need to include withPivot('id') in your relationship method in the model. i.e.

 function notifications() { return $this->belongsToMany('App\Notification')->withPivot('id'); } 
0
source

Source: https://habr.com/ru/post/1212785/


All Articles