How do I get users last message using hasMany with laravel - laravel

Message Tables Column is
| messages_id(pk) | user_id | target_id | message | created_at
User_id has sender user's id. Target_id has receiver user's id
And simple user table has relation to MessageTable by HasMany.
public function message()
{
return $this->hasMany('App\Model\TableModel\Message', 'user_id', 'user_id');
}
I want to get Userdata and each last message from user_id=[1,2,3,4] to target_id = 5.
So I tried this
User::WhereIn(user_id, [1,2,3,4])
->with(['message' => function ($query) {
$query->Where('target_id', 5)->orderBy('messages_id', 'desc)->first();
}])->get();
But this query return User's data and one user last message.
How do I get users last message using hasMany ?

your hasMany relation is incorrect:
the third argument should be the primary key of the current model:
public function message()
{
return $this->hasMany('App\Model\TableModel\Message', 'user_id', 'id');
}
anyway, to get the last message, I recommend building a new relation using hasOne relation:
public function lastMessage()
{
return $this->hasOne('App\Model\TableModel\Message', 'user_id', 'id')->latest();
}
now, you can use this new relation like:
User::WhereIn(user_id, [1,2,3,4])
->with(['lastMessage' => function ($query) {
$query->Where('target_id', 5);
}])->get();

Related

How to find rate in many to many relation if both foreign key match?

This is my User Item Pivot Table
| item_id | user_id | rate |
and i have defined many to many relation in both User and Item Model
This is my User Model
public function items()
{
return $this->belongsToMany(Item::class, 'item_user')->withPivot('rate');
}
This is my Item Model
public function users()
{
return $this->belongsToMany(User::class, 'item_user')->withPivot('rate');
}
This is My Controller.Suppose I have item_id.I want to find rate of where user and item_id id match.
public function findRate(Request $request){
$user=User::where('id',auth()->user()->id)->first();
$item_rate=$user->items->where('item_id', '1')->first();
dd($user);
return response()->json([
'item_rate'=>$item_rate,
]);
}
I tried like this but Error say Property [pivot] does not exist on this collection instance
$item_rate=$user->items->where('item_id', '1')->pivot()->rate;
Try this
$item_rate=$user->items()
->where('item_id',1)
->first()
->pivot
->rate;

get relatinal column HasManyThrough, set in response

i have craete membership that user can purchase one time of get all users with their membership and when they have purchase and when expired i'm confuse with this how to get my table structure is as:
User Model:
id
membership_id
public function membership() {
return $this->belongsTo(Membership::class);
}
Order:
id
user_id
public function item() {
return $this->hasOne(OrderItem::class, 'order_id', '_id');
}
order_item:
order_id
membership_id
created_at
expiration_date
public function membership() {
return $this->belongsTo(Membership::class, 'membership_id', '_id');
}
public function order() {
return $this->belongsTo(Order::class, 'order_id', '_id');
}
membership:
id
name
type
I want get data on time of listing like this how to load relation:
user{
name
email
membership{
name
type
order_item{
expiration_date
created_at
}
}
}
In membership model create this relation.
public function orderitems() {
return $this->hasOne(OrderItem::class, 'membership_id', 'id');
//It's upto you to confirm that whether it is a one-to-one or one-to-many relation
}
Then inside controller you can do something like
User::with('membership.orderitems')->get();
Updated
Alternatively you can create this hasManyThrough relation which will give you all order_items related users. Place this relation inside User Model.
public function items()
{
return $this->hasManyThrough( //please also check hasOneThrough according to your need
'App\OrderItem',
'App\Order',
'user_id', // Foreign key on order table...
'order_id', // Foreign key on order_item table...
'id', // Local key on users table...
'id' // Local key on order table...
);
}

Retrieve related models using hasManyThrough on a pivot table - Laravel 5.7

I'm trying to retrieve related models of the same type on from a pivot table.
I have 2 models, App\Models\User and App\Models\Group and a pivot model App\Pivots\GroupUser
My tables are have the following structure
users
id
groups
id
group_user
id
user_id
group_id
I have currently defined relationships as
In app/Models/User.php
public function groups()
{
return $this->belongsToMany(Group::class)->using(GroupUser::class);
}
In app/Models/Group.php
public function users()
{
return $this->belongsToMany(User::class)->using(GroupUser::class);
}
In app/Pivots/GroupUser.php
public function user()
{
return $this->belongsTo(User::class);
}
public function group()
{
return $this->belongsTo(Group::class);
}
I'm trying to define a relationship in my User class to access all other users that are related by being in the same group. Calling it friends. So far I've tried this:
app/Models/User.php
public function friends()
{
return $this->hasManyThrough(
User::class,
GroupUser::class,
'user_id',
'id'
);
}
But it just ends up returning a collection with only the user I called the relationship from. (same as running collect($this);
I have a solution that does work but is not ideal.
app/Models/User.php
public function friends()
{
$friends = collect();
foreach($this->groups as $group) {
foreach($group->users as $user) {
if($friends->where('id', $user->id)->count() === 0) {
$friends->push($user);
}
}
}
return $friends;
}
Is there a way I can accomplish this using hasManyThrough or some other Eloquent function?
Thanks.
You can't do that using hasManyThrough because there is no foreign key on the users table to relate it to the id of the group_user table. You could try going from the user to their groups to their friends using the existing belongsToMany relations:
app/Models/User.php:
// create a custom attribute accessor
public function getFriendsAttribute()
{
$friends = $this->groups() // query to groups
->with(['users' => function($query) { // eager-load users from groups
$query->where('users.id', '!=', $this->id); // filter out current user, specify users.id to prevent ambiguity
}])->get()
->pluck('users')->flatten(); // massage the collection to get just the users
return $friends;
}
Then when you call $user->friends you will get the collection of users who are in the same groups as the current user.

Laravel - Get articles from feeds for one user

I have three tables:
articles :
id
feed_id
title
feeds :
id
user_id
name
users :
id
name
I want get all articles from feeds for one user, I search the Eloquent Relationships...
Could you help me please?
First, define the relation on User model. Best option for you situation is to use a Has Many Through relation:
public function articles()
{
return $this->hasManyThrough(
'App\Article',
'App\Feed',
'user_id', // Foreign key on feeds table...
'feed_id', // Foreign key on articles table...
'id', // Local key on users table...
'id' // Local key on feeds table...
);
}
Then make a user object and get his articles:
$user = /App/User::with('articles')->find($id);
foreach($user->articles as $article) {
// do whatever you need
}
laravel documentation is always a good start for researching, read about hasManyThrough
https://laravel.com/docs/5.5/eloquent-relationships#has-many-through
don't mind if it is in 5.5, there are no significant differences between them
in model
in Articles.php
public function Feed()
{
return $this->belongsTo('App\Feed');
}
in Feed.php
public function User()
{
return $this->belongsTo('App\User');
}
public function Articles()
{
return $this->hasMany('App\Articles');
}
in User.php
public function Feed()
{
return $this->hasMany('App\Feed');
}
in controller
// To get all articles of user with id = $id
$reports2 = Articles::with(array('Feed'=>function($query)use($id){
$query->with('User');
$query->where('user_id',$id);
}))->orderBy('id', 'desc')
->get();

What kind of relationship should be?

I have two models: Users and Categories.
I need to get all categories on which user subscribed.
Do, database structure is:
User Category UserCategory
___ _________ __________
id id | name category_id user_id
Category model is:
public function user()
{
return $this->belongsToMany('App\User', 'user_id', 'id');
}
User model is:
public function categories()
{
return $this->belongsToMany('App\Category');
}
I tried to get all categories on which user subscribed through third table:
$categories = Category::with("user")->where("id", Auth::user()->id)->get();
It does not work for me
To get all categories which belong to the user, use the whereHas() method:
$categories = Category::whereHas('users', function($q) use($userId) {
$q->where('id', $userId);
})->get();
Also, make sure table name is categories_users and define users relationship like this:
public function users()
{
return $this->belongsToMany('App\User');
}

Resources