Md Majadul Islam
Md Majadul Islam

Reputation: 125

laravel model relationship 5.5

1. users
1. id
2. name

2. categories
1. id
2. category_name
3. user_id

3. posts
1. id
2. post_title
3. category_id

So now I want to show data in my view
like : post_title->category_name->user_name

How to do in laravel query relationship in model

Upvotes: 0

Views: 73

Answers (2)

Mahdi Younesi
Mahdi Younesi

Reputation: 7489

Define the relationships

class Post extends Model
{
    return $this->blongsTo(Category::class);
}

class Category extends Model
{
    return $this->blongsTo(User::class);
}

Now

$post = with('category.user')->whereId(1)->first(); //1 is my guess

$post->category()->user->name();

Also it seems like a has-many-through relationship though you can access a user's post like this

$user->posts;

For that you need to define:

class User extends Model
{
/**
 * Get all of the posts for the user.
 */
public function posts()
{
    return $this->hasManyThrough(Post:class, Category::class);
}
}

Upvotes: 1

Ahmed Shams
Ahmed Shams

Reputation: 358

$Query=DB::select('select posts.post_title,categories.category_name,
users.name from posts,categories,users where users.id=categories.user_id and
categories.id=posts.category_id');

if you dont use DB:: you can use your model

$Query = Users::select('users.name', 'posts.post_title', 'categories.category_name')
        ->join('categories', function ($join) {
             $join->on('categories.user_id', '=', 'users.id')
                  ->join('categories.id', '=', 'posts.category_id');
    })
        ->get();

check spell table name and columns but if there is duplicate in data it wont work

Upvotes: 0

Related Questions