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

Php 如何在Laravel模型关系中传递参数,php,laravel,eloquent,relation,Php,Laravel,Eloquent,Relation,我做了一个分类树,我需要向relation传递一个参数,我不能传递它们 public function Child() { return $this->hasMany(Category::class, 'parent_id', 'id'); } 但我想用变量传递关系,如下所示 public function Child() { return $this->hasMany(Category::class, 'parent_id', 'id')->where(['

我做了一个分类树,我需要向relation传递一个参数,我不能传递它们

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]);
}
然后我尝试使用变量,但什么也不接收,但若我使用硬编码值,那个么效果会很好。请帮助

$models=App\{YourMainModel}::使用['Child'=>函数$query使用$this{ $query->where['owner\u id'=>$this->ownerId]; }]->得到; $models=App\{YourMainModel}::with['Child'=>函数$query使用$this{ $query->where['owner\u id'=>$this->ownerId]; }]->得到;
您需要将构造函数添加到扩展类模型的子模型中

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);
}
如果每次要实例化类子级时,都必须给它一个所有者,则可以这样做:

$ownerId = 5;
$child = new Child($ownerId);
或者,您可以从调用该函数的任何位置直接将参数传递给该函数,如:

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


作为提示,我建议您以小写字母开头函数名。

您需要向子模型添加一个构造函数,以扩展类模型

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);
}
如果每次要实例化类子级时,都必须给它一个所有者,则可以这样做:

$ownerId = 5;
$child = new Child($ownerId);
或者,您可以从调用该函数的任何位置直接将参数传递给该函数,如:

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


作为提示,我建议您以小写字母开头函数名。

您的列实际上是名为ownerId还是名为ownerId?不,我的模型中有此参数,但我在调用此关系后设置了值。我认为这不可能。您可能需要在没有where子句的情况下保留关系,然后使用您的条件和变量创建一个查询范围。您的列实际上被称为ownerId还是也被称为ownerId?不,我的模型中有这个参数,但我在调用这个关系后设置了值。我认为这是不可能的。您可能需要在没有where子句的情况下保留关系,然后使用您的条件和变量创建一个查询范围。在我的情况下不起作用。我使用两个关系来获取所有子模型。在我的案例中,您可以通过链接“不工作”来了解更多信息。我使用两种关系来获取所有子模型。您可以通过链接了解更多信息