【问题标题】:Laravel eloquent one to many relation where statementLaravel 雄辩的一对多关系 where 语句
【发布时间】:2015-05-17 14:44:51
【问题描述】:

我在 laravel eloquent 中有以下模型

class InterviewList extends Eloquent{

protected  $table = 'interviewlists';

public function subject(){
    return $this->belongsTo('Subject','id_subject','id');
}}

class Subject extends Eloquent{

public  function interviewList(){

    return $this->hasMany('InterviewList');
}}

我需要获取主题名称为“java”的 interviewList 表的 ID, 在主题表中,我有(id,name)列,在 interviewList 表中(id,name,id_subject)。 我试过下面的代码

 $interviewListId = InterviewList::with('Subject')->whereName('java')->get(array('id'));

但它只是没有结果

【问题讨论】:

    标签: php mysql laravel laravel-4 eloquent


    【解决方案1】:

    这样的事情怎么样

    Subject::where('name', 'like', '%java%')-> interviewList()->get(array('id'));
    

    【讨论】:

      【解决方案2】:

      要获取主题名称为 java 的采访列表的 ID,您应该使用:

      $ids = InterviewList::whereHas('subject',  function($q)
      {
          $q->where('name', 'java');
      
      })->lists('id');
      

      【讨论】:

      • 效果很好,但是只有一个问题,这个函数会从数据库中获取所有显示“id”的列,还是获取更快的 jus id 列?
      • @Redadublex 它将在 DB 查询中从分配给 InterView List 模型的表中获得 id
      猜你喜欢
      • 2012-10-08
      • 2018-10-27
      • 1970-01-01
      • 2018-11-14
      • 2015-07-01
      • 1970-01-01
      • 2014-09-20
      • 2014-01-03
      • 2019-03-10
      相关资源
      最近更新 更多