Hello i have 2 table (Users and Posts) with 1 to many realtionship.
I want to retrive all data in one single query by eloquent and result should be as follow
Users table: id | name
Posts Table: id | user_id | title| body
retrived data should be
name | title | body
Eager load the data:
$data = User::with('posts')->get();
In a view:
@foreach ($user->posts as $post)
{{ $post->title }}
@endforeach
If you mean you want to make Laravel create just one query to the DB, you can get all posts with:
$posts = Post::where('user_id', $userId)->get();
尝试这个
User::join("posts","posts.user_id","=","users.id")->get();
Try running the following query in MySQL. It should work.
select name,title,body from Users,Posts where Users.id=Posts.id group by Users.id
In Post model create the following code in laravel 8.0.x:
public function user()
{
return $this->belongsTo(User::class);
}
In view just call the attribute:
$post->user->name;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.