查询hasMany与slug而不是id的关系?

时间:2018-08-01 03:49:22

标签: laravel laravel-5 eloquent

我正在尝试根据某类查询类别及其所有渠道。

工程

\App\Category::find(1)->channels()->get();

无效

\App\Category::where('slug','animals')->channels()->get()
  

BadMethodCallException,消息为“方法照亮/数据库/查询/生成器::通道不存在。”

类别模型的关系

public function channels()
{
    return $this->hasMany(Channel::class,'category_id');
}

2 个答案:

答案 0 :(得分:1)

假设您在迁移和模型属性中正确设置了 slug 字段(从 Exception 消息中可以看到)。

\App\Category::find(1)->channels()->get();

等同于

\App\Category::where('category_id', 1)->first()->channels()->get();

因此,您需要的是get类别以实际执行查询,然后能够从水合模型中检索渠道。

\App\Category::where('slug', 'animals')->first()->channels()->get();

应该和

一样好

\App\Category::where('slug', 'animals')->first()->channels; // calling as attribute will perform the get() on the relationship

还请注意,您可能会利用with()之类的其他方法来急于加载关系,first()来执行获取并确保您仅获取一个实例,并将该关系作为属性调用为如上所示。请参阅docs

答案 1 :(得分:0)

您的问题中有太多可能的答案..更具体..但是这是一些可能对您有所帮助的示例查询列表。

使用分类标记=动物的频道获取所有分类

Category::with(['channels'])->where('slug', 'animal')->get();

获取具有频道段=动物的频道的所有类别

Category::with(['channels'])->whereHas('channels'=>function($q){
    $q->where('slug','animal');
})->get();

仅使用带有子句=动物的频道来获取所有类别

Category::with(['channels'=>function($q){
    $q->where('slug','animal');
}])->get();