A
A
Aizharik2015-01-27 14:43:39
MySQL
Aizharik, 2015-01-27 14:43:39

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]);

How can this be done in laravel

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
vladflip, 2015-01-27
@aizhar777

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(); // вернет одним запросом посты со своими юзерами

E
Eugene, 2015-01-27
@Nc_Soft

You just need to read the laravel.com/docs/4.2/eloquent#eager-loading doc

6
65536, 2015-01-27
@65536

with

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question