where function in belongsToMany problem

Posted 1 year ago by arctushar

Wanted to select nodes that have tag id 4 in NodeController I am using below function

$nodes=Node::with(['tags'=>function($query)use ($id){
            $query->where('tags.id','4');
        }])->paginate(12);

I have also tried to use 4 instead of '4' and also tried in NodeController as below

$nodes=Node::with(['tags'=>function($query)use ($id){
            $query->where('tag_id','4');
        }])->paginate(12);

and I have below models Node model is as below

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

Tag table has below field ['id','name'] and tag models is as below

class Tag extends Model
{
    public function node(){
        return $this->belongsToMany('App\Node');
    }
    public $timestamps = false;
}

My node_tag table has id,node_id,tag_id fields. all above cases not showing error but result is all nodes id 1-12, whether tag_id is 4 or not What is the problem and what is the solution ?

NB: my pivot table name is node_tag

Please sign in or create an account to participate in this conversation.