How to get authors (users) using eager lazy loading?

  • 0
    I'm doing something like social. networks. Profile page. I get user posts. It is necessary to get more authors of posts, if any. But I don't know how to do it (

    User Model:
    /* Получаем данные по пользователю */
    	public static function getUser(string $login = null){
    		return User::where('login_users', $login)->first();
    	}
    
    	/* Получаем все зависимости */
    	public static function withUser(string $login){
    		$user = User::getUser($login);   // Получаем данные о пользователе
    
    		// "Делаем ленивую нетерпеливую загрузку"
    		if($user){
    			$user->load(['posts']);
    		}
    
    		return $user;    // Отдаём эти данные
    	}
    
    	/* Получаем все посты от пользователя */
    	public function posts(){
    		return $this->hasMany(Posts::class, 'user_posts', 'id_users');
    	}
    
    	/* Получаем всех авторов постов (не так получается) */
    	public function authorPosts(){
    		return $this->hasMany(Posts::class, 'userAdd_posts', 'id_users');
    	}


    This code displays the data of the user himself and the posts from his page. But now we need to get more authors by userAdd_posts (posts table). How to do this?

    Posts table
    MySQL Anonymous, Sep 5, 2020

  • 4 Answers
  • 0
    why are you adding "noise" to the model? than your static getUser method which will be called like

    User :: getUser ($ login) is better than User :: whereLogin ($ login) - & gt; first ()? I would still understand if this getByLogin method in UsersRepository. static method withUser is generally nonsense - User :: withUser ($ login) - wat?

    The naming of the fields made me cry.

    Why make a greedy load for one object?


    Well, and most importantly, there is no question in your question.
    Anonymous

  • 0
    Hehehehe ... found a solution to the problem in a magical way, I'll post the code here. Thanks to everyone who helped, especially ellrion , who provided good code for further editing!


    User Model:
    /* Получаем все зависимости */
    public static function withUser(string $login){
    $user = User::where('login_users', $login)->first(); // Получаем данные о пользователе
    $user->load(['getUserPosts.author']);

    return $user; // Отдаём эти данные
    }

    /* Получаем все посты со страницы пользователя */
    public function getUserPosts(){
    return $this->hasMany(Posts::class, 'user_posts', 'id_users');
    }



    Model Posts:
    /* Получаем авторов поста */
    public function author(){
    return $this->belongsTo(User::class, 'author_posts', 'id_users');
    }



    Well, the controller itself (there is nothing magic):
    $ withUser = User :: withUser ($ login);
    Anonymous

  • 0
    When such a quantity of data and connections is involved, it is better to convert to pure mysql queries, otherwise it will flow and, in general, it will slow down on big data
    Anonymous

  • 0
    Seems like you wanted to create a "bookmark post" for the user?

    To do this, create a third table. As a result, you have three tables.
    users: id name login email ...
    posts: id title body slug author_id
    < b> users_posts: user_id post_id // posts in bookmarks


    RouteServiceProvider.php
    public function boot()
    {
    parent::boot();

    Route::model('user', App\User::class);
    Route::model('post', App\Post::class);
    }



    web.php
    Route::get('profile/{user}', '[email protected]')
    Route::get('posts/{post}', '[email protected]')


    User.php
    public function getRouteKeyName()
    {
    return 'login';
    }

    public function posts_feed()
    {
    return $this->belongsToMany('App\Post');
    }

    public function posts()
    {
    return $this->hasMany('App\Post', 'author_id');
    }



    Post.php
    public function getRouteKeyName()
    {
    return 'slug';
    }

    public function author()
    {
    return $this->belongsTo('App\User');
    }


    class ProfileController extends Controller
    {
    public function show(User $user)
    {
    $user->load('posts_feed.author')
    return view('profile', compact('user'))
    }
    }


    In show.blade.php
    {{ $user->name }}
    @foreach(user->posts_feed as $post)
    {{ $post->title }}
    {{ $post->author->name }}
    @endforeach
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!