Answer the question
In order to leave comments, you need to log in
How to get authors (users) using eager lazy loading?
I do 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(
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');
}
Answer the question
In order to leave comments, you need to log in
why are you adding "noise" to the model? than your static getUser method which will be called as
User::getUser($login) is better than User::whereLogin($login)->first()? I would also understand if this getByLogin method is in UsersRepository. the static method withUser is generally nonsense - User::withUser($login) - wat?
The naming of fields made me cry.
What for to do greedy lazy loading for one object?
Well and the main thing in your question is not a question.
When such a number of data and connections are involved, it is better to convert to pure mysql queries, otherwise it will flow and, in general, will slow down on big data
It seems you wanted to create a la "bookmarked posts" for the user?
To do this, create a third table. As a result, you have three tables.
users_posts: user_id post_id // bookmarked posts
RouteServiceProvider.php
public function boot()
{
parent::boot();
Route::model('user', App\User::class);
Route::model('post', App\Post::class);
}
Route::get('profile/{user}', '[email protected]')
Route::get('posts/{post}', '[email protected]')
public function getRouteKeyName()
{
return 'login';
}
public function posts_feed()
{
return $this->belongsToMany('App\Post');
}
public function posts()
{
return $this->hasMany('App\Post', 'author_id');
}
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'))
}
}
{{ $user->name }}
@foreach(user->posts_feed as $post)
{{ $post->title }}
{{ $post->author->name }}
@endforeach
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question