如何在Laravel模型关系中传递参数

问题描述 投票:0回答:2

我制作了一个类别树,我需要传递一个参数来关联,我不能传递它们。

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

但是我想使用变量来传递这种关系。

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

然后,我尝试使用变量,但是什么也不会收到,但是如果我使用硬编码值,那么效果很好。请帮助

php laravel eloquent relation
2个回答
1
投票
$models = App\{YourMainModel}::with(['Child' => function ($query) use ($this) {
    $query->where(['owner_id' => $this->ownerId]);
}])->get();

0
投票

您将需要向子模型添加一个构造函数(这将扩展Model类)。

private ownerId;

public function __construct(int ownerId)
{
    parent::__construct($attributes);

    $this->ownerId = $ownerId;
}

然后您可以在整个课程中访问它。

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

如果每次想实例化类Child时,都必须给它一个所有者:

$ownerId = 5;
$child = new Child($ownerId);

或者,您可以从任何调用它的位置直接将参数传递给该函数,例如:

public function childWithOwner(int $ownerId)
{
    return $this->hasMany(Category::class, 'parent_id', 'id')->where('owner_id', $ownerId);
}

您会称之为:$this->childWithOwner(4);

作为提示,我鼓励您以小写字母开头函数名称。

© www.soinside.com 2019 - 2024. All rights reserved.