I have 2 models: subscribe and user
Model subscribe contains accept and user_id field. This model belongs to user model. And now - I want to make model function which in first step filter only accept subscribe and second step display users. I don't have idea how can I do that. I know that I can make this method in user model but is it possible to make this function inside subscribe model?
I tryed do like that but it doesn't work. Any idea?
public function activeSubscribes() {
$instance = $this->where('user_id', 1)
->belongsTo(User::class);
return $instance;
}
CodePudding user response:
create a local scope like this , and put you're condition inside the function , and thit function need two arguments
public function activeSubscribesForUser($query,User $user)
{
return $query->where([
'user_id' => $user->id,
'accept' => 'accepted',
]);
}
CodePudding user response:
You can add in your user model this code
public function activeSubscribes()
{
return $this->whereHas('subscribes', function ($q){
$q->where('accept', 1); //your condition
});
}
public function subscribes()
{ //Also maybe you need hasOne relation
return $this->hasMany(Subscribes::class);
}
Then you can use it like this
User::activeSubscribes()->get()