拉拉维尔雄辩检索特定信息


Laravel Eloquent retrieve specific information

我刚刚开始使用Laravel Eloquent 并坚持检索一些数据。如果有人能指导我,那就太好了。

我有两个表(没有提到用户表)

研究所

 id    |name   | user_id 
 1     |abc    |22       
 2     |xyz    |32        

现在研究所2(xyz)有以下程序

程序

 id     |institute_id| name | admission_open|
  1     | 2          |exp1  | 1             |
  2     | 2          |exp2  | 0             |

研究所.php

class Institute extends Eloquent
{
  protected  $table = 'institutes';
  public function programs(){
    return $this->hasMany('Program');
   }
}

程序.php

class Program extends Eloquent
{
   protected  $table = 'programs';
   public function institute()
   {
    return $this->belongsTo('Institute');
   }
}

我想要什么:

我想在课程表中获取招生 (admission_open =1) 的机构名称。

我应该如何为 that.do 必须联接表编写查询?

$tests = Programs::where('admission','1')->get();

现在,在获取对象后,您可以循环

 foreach($tests as $test) {
$test->institute->name;
}

有很多方法可以做到这一点。就像用户@ujwal dhakal 说的或加入一样,但我更喜欢这个:

Institute:::whereHas('program', function($query) {
    $query->where('admission', '=',1);
})->get();
$institutions = Institute:::whereHas('programs', function($query) {
                   $query->where('admission_open', '=',1);
                })->get();

希望这有帮助

你可以

试试

$programs = Program::where('admission_open','1')->with('institute')->get();

$programs = Program::where('admission_open','=','1')->with('institute')->get();

$programs将具有 admission_open = 1 的程序对象和机构数据

foreach($programs as $program){
       echo $program->institute->name;
}