Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameter in Laravel model relation

I made a category tree and I need to pass one parameter to relation, I can't pass them.

public function Child()
{
    return $this->hasMany(Category::class, 'parent_id', 'id');
}

but I want to use variable to pass in relation look like this.

public function Child()
{
    return $this->hasMany(Category::class, 'parent_id', 'id')->where(['owner_id' => $this->ownerId]);
}

then I try to use variable and receive nothing, but if I use hardcoded value then works well. Please help

like image 566
Стас Чурилов Avatar asked Oct 14 '25 15:10

Стас Чурилов


1 Answers

$models = App\{YourMainModel}::with(['Child' => function ($query) use ($this) {
    $query->where(['owner_id' => $this->ownerId]);
}])->get();
like image 52
Serhii Posternak Avatar answered Oct 17 '25 04:10

Serhii Posternak