Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
laravel:如何将参数传递给模型中的函数?_Laravel - Fatal编程技术网

laravel:如何将参数传递给模型中的函数?

laravel:如何将参数传递给模型中的函数?,laravel,Laravel,我使用的是Laravel5.5/PHP7.2/ 例如,我在模型中有这样一个函数: public function featuredTopSight($count=8) { return $this->hasMany(Sight::class) ->wherePublish(1) ->latest() ->take($count); } 然后,鉴于: $sight->featuredTopSight(8);

我使用的是Laravel5.5/PHP7.2/

例如,我在模型中有这样一个函数:

public function featuredTopSight($count=8)
{
    return $this->hasMany(Sight::class)
        ->wherePublish(1)
        ->latest()
        ->take($count);
}
然后,鉴于:

$sight->featuredTopSight(8);
但我有一个错误:

"htmlspecialchars() expects parameter 1 to be string, object given

但是使用
$sight->featuredTopSight在该函数中,您定义的是关系

不能调用带有参数的关系

首先需要声明关系,然后是检索结果的查询或方法

您的方法应类似于:

public function sights()
{
    return $this->hasMany(Sight::class);
}

public function getFeaturedTopSights($count = 8)
{
    return $this->sights()->wherePublish(1)->latest()->take($count)->get();
}

是否可以共享您的完整视图代码?