Reputation: 878
I have a users_table and user_tweets_table in Laravel / MySQL.I want to return response data in this structure:
[
{
id:1,
name:'Johne',
tweets:[
{
id:1,
content:"something"
},
{
id:2,
content"something else"
}
]
},
{
id:2,
name:'Jennifer',
tweets:[
{
id:1,
content:"something"
},
{
id:2,
content"something else"
}
]
},
]
I try this one but it's not good:
$list = User::all();
$list = $list->
skip($skip)->
take($take);
foreach ($list as $user)
{
$user['tweets']=UserTweet::where('user_id',$user['id'])->get();
}
return response(['message' => 'The list of users', 'data' => $list], 200);
how can I do that with eloquent and innerjoin?
Upvotes: 0
Views: 193
Reputation: 12188
you should build the relation between your models ...
in User Model:
public function tweets()
{
return $this->hasMany(UserTweet::class, 'user_id');
}
in UserTweet Model:
public function user()
{
return $this->belongsTo(User::class,'user_id');
}
now you can load your relation:
$list = User::with('tweets')->all();
more about one to many relation in doc
Upvotes: 1