Eloquent query - one to many relationship - laravel

Guys I'm new to Laravel and I'm trying to find the name of the user that answers a certain question:
$users = User::with('answers')->where('question_id', $request->question_id)->get();
I've tried this but it doesn't work.It seems like he is trying to find the question_id from the User and not from the Answer.
Answer Model
Class Answer extends Model{
public function users()
{
return $this->belongsTo(User::class);
}
}
User Model
Class User extends Authenticatable{
public function answers()
{
return $this->hasMany(Answer::class);
}
}

This is what you need, Constraining Eager Loads.
$users = User::with(['answers' => function ($query) use ($request) {
$query->where('question_id', $request->question_id)
}])->get();

This is not what you asked for but maybe what you need:
$answers = Answer::with('user')->where('question_id', $request->question_id)->get();

Related

Eloquent collections with a relation of another relation

I have Post eloquent related with PostCategory and my collection is good.
class Post extends Model
{
public function post_categories()
{
return $this->belongsTo(PostCategory::class, 'category_id');
}
public function detail($slug_category, $slug)
{
$detail = Post::with('post_categories')
->whereHas('post_categories', function ($query) use ($slug_category){
$query->where('category_slug', $slug_category);
})->where('slug', $slug)
->first();
return($detail);
}
}
I have this another class 'Players' where i need to have a collection with all user's posts with PostCategory category relation.
class Players extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
public function detail($slug_category, $slug_name)
{
$detail = Player::with('posts')
->whereHas('players_info', function ($query) use ($slug_name){
$query->where('slug', $slug_name);
})
->whereHas('player_categories', function ($query) use ($slug_category){
$query->where('category_slug', $slug_category);
})->first();
return($detail);
}
}
I read something about "belongsToMany" and "withPivot", but I'm still confused for correct way.
What can I do to resolve this?
thanks!
I solved just with this.
return $this->hasMany(Post::class)->with('post_categories');

How to get tweets including my tweets with 1query by Eloquent Laravel?

I’m building like Twitter to learn Laravel.
I want to get the information of Tweets which I follow, and including my Tweets with 1 query.
This is the model of relationships.
Please check, I only take the information about relationships.
Please give me advice.
Follow Model
class Follow extends Model {
Public function user(){
return $this->belongsTo(User::class, "followed_user_id", "id");
}}
Tweet Model
class Tweet extends Model {
Public function user(){
return $this->belongsTo(User::class, "user_id");
}}
User Model
class User extends Model{
Public function tweet(){
return $this->hasMany(Tweet::class);
}
Public function followUsers(){
return $this->hasMany(Follow::class, "follow_user_id");
}
Public function followedUsers(){
return $this->hasMany(Follow::class, "followed_user_id");
}}
If you want to get all the users with his all the tweets you can simply use
User::with('tweets')->get();
If you want to get the tweets of a single user in a single query you can
User::with(['tweets' => function($query) use ($userId){
$query->where('user_id', $userId);
}])->first()

Merging two queries into one using Eloquent

I have this two queries to display information in 3 tables Users, Comments, and Posts. so I made this function:
public function show($id)
{
$posts = Post::with(['comments'])->findOrFail($id);
$user = User::find($posts->user_id);
echo "<h1>".$posts->title.'</h1>';
echo "<h2>".$user->name.'</h2>';
foreach ($posts->comments as $comment) {
echo $comment->body.'<br>';
}
}
on this function I using two variable $posts and $user, can I merge this two variable using eloquests command like Post::with(['user','comments'])'? so I can use just $posts variable and use it like $posts->users->name to access user name.
i was trying using this way:
$posts = Post::with(['comments','users'])->findOrFail($id);
but when i echo the post it showing that the user was null:
{"id":1,"user_id":1,"title":"Oleh id 1","body":"ini adalah content","created_at":"2017-10-18 03:25:54","updated_at":"2017-10-18 03:25:54","comments":[{"id":1,"post_id":1,"body":"Keren banget deh artikelnya, TOP","created_at":"2017-10-18 03:43:50","updated_at":"2017-10-18 03:43:50"},{"id":2,"post_id":1,"body":"Keren banget deh artikelnya, TOP","created_at":"2017-10-18 03:43:53","updated_at":"2017-10-18 03:43:53"},{"id":3,"post_id":1,"body":"Keren banget deh artikelnya, TOP","created_at":"2017-10-18 03:43:54","updated_at":"2017-10-18 03:43:54"}],"users":null}
Here's my model if you need it. My post model:
class Post extends Model
{
/**
* Get the comments for the blog post.
*/
public function comments()
{
return $this->hasMany('App\Comment');
}
public function users(){
return $this->belongsTo('App\User');
}
}
my Comment model
class Comment extends Model
{
/**
* Get the post that owns the comment.
*/
public function post()
{
return $this->belongsTo('App\Post');
}
}
You’ll have an easier time sticking to Laravel’s conventions for naming relationships.
A Post has many Comments, which belong to a User. Given this set up:
class Post extends Model
{
public function comments()
{
return $this->hasMany(Comment::class);
}
}
class Comment extends Model
{
public function post()
{
return $this->belongsTo(Post::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
}
You can then query a post’s comments and users like this:
$comments = $post->comments()->with('user')->get();
You could also eager-load the user relation on comments if you always wanted the user returned with a comment:
class Comment extends Model
{
protected $with = ['user'];
public function user()
{
return $this->belongsTo(User::class);
}
}
Then your query would be simplified:
$comments = $post->comments;
Hope this helps you!!
What I am guessing is you want the list of all posts with the users. If relation is defined, try with the join
$posts = DB::table('posts')
->join('users', 'users.id', '=', 'posts.user_id')
->select('posts.*', 'users.name as user_name')
->where('posts.comments', '<>', NULL)
->get();
#NOTE: If you are using soft deletes you might wanna add where('posts.deleted_at', null)
After couple of days searching finally i got the answer, i can get merge the query like this:
$posts = Post::with(['comments','users'])->findOrFail($id);
but in the Post Model the function not "Users" but "User".

Laravel Eloquent - Get all records of child relation model

My data model is this:
Users > Offices > Organization
This is my model
class Organization extends Model {
protected $table = 'organizations';
public function offices()
{
return $this->hasMany('App\Models\Office');
}
public function users()
{
return $this->offices()->users();
}
....
So.. I want to get all users from an organization (of all the offices).
But I don't know how to do something like
$this->offices()->users();
(Avoiding user a manual collection or map to do that)
Thanks!
So, you have organization ID. You can load all users by using whereHas():
$users = User::whereHas('office', function ($q) use ($organizationId) {
$q->where('organization_id', $organizationId);
})
->get();
Make sure office() relationship is defined correctly in User model:
public function office()
{
return $this->belongsTo('App\Office');
}
Alternatively, you could define hasManyThrough() relationship:
public function users()
{
return $this->hasManyThrough('App\Office', 'App\User');
}
And use it:
$organization->users()

Laravel 5 - Eloquent: easier way to filter a many to many relationship

I have a many to many relationship between Lists and Users.
This is the List Model:
class ListModel extends Model
{
protected $table = "lists";
public function users()
{
return $this->belongsToMany('App\Models\User', 'list_user', 'list_id', 'user_id')->withTimestamps();
}
}
This is the User model:
class User extends Authenticatable
{
public function lists()
{
return $this->hasMany('App\Models\ListModel');
}
}
In a list page, I need to get all the lists belonging to the logged user. The only solution I found is this one:
$user = \Auth::user()->id;
$all_lists = ListModel::whereHas('users', function ($query) use ($user) {
$query->where('user_id', $user);
})->active()->get();
is there any simpler way to achieve the same result?
Since current user is already loaded, you can use lazy eager loading to load lists for the user:
auth()->user()->load('lists');
Your lists() relationship is not defined correctly. The inverse of belongsToMany is still belongsToMany (hasMany's inverse is belongsTo):
class User extends Authenticatable
{
public function lists()
{
return $this->belongsToMany('App\Models\ListModel', 'list_user', 'user_id', 'list_id')->withTimestamps();
}
}
Then you can get the lists like this:
$user = \Auth::user();
$all_lists = $user->lists()->active()->get()

Resources