Answer the question
In order to leave comments, you need to log in
Query related tables Mysql PHP Laravel?
Good day, the essence of the question is this:
How to get data from a linked table, or rather, how to do it correctly?
Let's say there is a Posts table, it is connected by user_id with the Users table. Let 's
assume that 50 posts are displayed, for each post I want to display information about the author of the post. there is the name of the avatar and something else. It only comes to mind to make a request to receive posts, and then, when displaying each post, make a request for the author. It turns out 51 requests to the database. I understand that you can do this with a join, but the query to the database is already so complicated, is it worth adding a join to it?
Here is the post request:
$userId =1;
$posts = DB::select('
(
SELECT * FROM posts
WHERE group_id IN ( SELECT group_id FROM groups_members WHERE user_id = ? )
OR user_id IN ( SELECT friend_id FROM friends WHERE user_id = ? )
OR user_id=?
)ORDER BY created_at DESC LIMIT 0, 50',
[$userId, $userId, $userId]);
Answer the question
In order to leave comments, you need to log in
use Eloquent relationships
// Post.php
class Post extends Eloquent
{
protected $table = 'posts'; // имя таблицы
public function user() {
return $this->belongsTo('User', 'user_id');
}
}
// User.php
class User extends Eloquent
{
protected $table = 'users'; // имя таблицы
public function posts() {
return $this->hasMany('Post', 'user_id');
}
}
Post::with('user')->get(); // вернет одним запросом посты со своими юзерами
You just need to read the laravel.com/docs/4.2/eloquent#eager-loading doc
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question