【问题标题】:Making a query through relation property in Laravel 4通过 Laravel 4 中的关系属性进行查询
【发布时间】:2014-08-19 21:35:18
【问题描述】:

我在艺术家和专辑之间有这种一对多的关系,一个艺术家可以与许多专辑相关,但一个专辑只能与一个艺术家相关联。

我的艺术家模型:

<?php


class Artist extends Eloquent {

  public function albums()
  {
      return $this->hasMany('Album');
  }

}

我的专辑型号:

<?php


class Album extends Eloquent {

  public function artist()
  {
      return $this->belongsTo('Artist');
  }

}

我学会了如何获取某个艺术家的所有专辑,以及如何检索专辑的艺术家。但是我还是不知道怎么做这个查询:

获取艺术家为“林肯公园”的所有专辑

我目前正在做的是:

$artist = Artist::where('name','=','Linkin Park')->first();

$albums = Album::where('artist_id','=',$artist->id)->get(); 

我得到了我需要的东西,但我想知道是否有其他方法可以做到这一点。类似的东西(我知道是错的):

$albums = Album::where('artist','=','Linkin Park');

【问题讨论】:

    标签: laravel laravel-4 relationship foreign-key-relationship


    【解决方案1】:

    没关系,我通过查看examples in the official documentation 找到了一种方法。

    查询应该是这样的:

    $albums = Album::whereHas('artist', function($q)
    {
        $q->where('name', '=', 'Linkin Park');
    
    })->get();
    

    【讨论】:

      猜你喜欢
      • 2020-05-30
      • 1970-01-01
      • 1970-01-01
      • 2021-07-23
      • 2020-05-12
      • 1970-01-01
      • 2021-12-02
      • 2021-02-24
      • 1970-01-01
      相关资源
      最近更新 更多