Prem Thakkar
Prem Thakkar

Reputation: 17

Laravel Model Query with "with" and "where condition" not working

This Query Of get bookmarks is working with condition without relation with user_topics

$bookmarkedposts = BookmarkedPost::where('leader_id',$user_id)->get();

But When I add add relation to other model it didn't work

$bookmarkedposts = BookmarkedPost::where('leader_id',$user_id)->with('user_topics.first_media')->get();

Here is Bookmarked.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class BookmarkedPost extends Model
{
   public function user_topics()
    {
        return $this->hasOne('App\UserTopic','id')->where('isdelete',0)->where('isactive',1);
    }
}

bookmarked_posts_table_sturucture user_topics_table_stucture

Upvotes: 0

Views: 408

Answers (2)

Alberto
Alberto

Reputation: 12919

BookmarkedPost Model:

class BookmarkedPost extends Model
{
   public function user_topic()
    {
        return $this->belongsTo('App\UserTopic','user_topic_id', 'id');
    }
}

UserTopic Model:

class UserTopic extends Model
{
   public function bookmarder_posts()
    {
        return $this->hasMany('App\BookmarkedPost','user_topic_id', 'id');
    }
}

Inside the function now you can use:

$bookmarkedposts = BookmarkedPost::where('leader_id',$user_id)->with('user_topic')->get();

Upvotes: 1

Jrb
Jrb

Reputation: 461

Try this

 BookmarkedPost::where('leade_id', $user_id)->with('user_topics');

Upvotes: 0

Related Questions