Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/10.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-从hasMany realtion获得第一个元素?_Laravel_Eloquent - Fatal编程技术网

Laravel-从hasMany realtion获得第一个元素?

Laravel-从hasMany realtion获得第一个元素?,laravel,eloquent,Laravel,Eloquent,我正在尝试获取每个类别的第一个元素 Category Class public function product() { return $this->hasMany(Product::class, 'category_id', 'id'); } public function first_product() { return $this->product()->limit(1); } 这是我的问题 $categories = Category::wit

我正在尝试获取每个类别的第一个元素

Category Class 

public function product()
{
    return $this->hasMany(Product::class, 'category_id', 'id');
}

public function first_product()
{
   return $this->product()->limit(1);
}

这是我的问题

 $categories = Category::with('first_product')->get();
我得到了第一个产品,只是类别的第一个元素。为什么?

尝试此操作以获取单个数据

public function first_product()
{
返回$this->hasOne(产品::类);
}
然后

$categories=Category::with('first_product')->get();

感谢您的回复。当我使用此查询时,它会在第50行的文件/home/vendor/laravel/framework/src/illumb/Support/Traits/ForwardsCalls.php中抛出以下错误:BadMethodCallException:Call到未定义的方法App\Models\Product::addagerConstraints()。它将只返回产品的最后一个元素?为什么?