简体   繁体   English

Laravel Eloquent 检索特定信息

[英]Laravel Eloquent retrieve specific information

I have just started using Laravel Eloquent and stuck at retrieving some data.我刚刚开始使用 Laravel Eloquent 并坚持检索一些数据。 It would be great if someone can guide me.如果有人可以指导我,那就太好了。

I have two tables (not mentioning user table)我有两个表(没有提到用户表)

Institutes :研究所

 id    |name   | user_id 

 1     |abc    |22       
 2     |xyz    |32        

Now institute2 (xyz) has following programs现在 Institute2 (xyz) 有以下程序

Programs :课程

 id     |institute_id| name | admission_open|

  1     | 2          |exp1  | 1             |
  2     | 2          |exp2  | 0             |

Institute.php研究所.php

class Institute extends Eloquent
{
  protected  $table = 'institutes';

  public function programs(){
    return $this->hasMany('Program');
   }

}

Program.php程序.php

class Program extends Eloquent
{
   protected  $table = 'programs';

   public function institute()
   {
    return $this->belongsTo('Institute');
   }
}

What I want:我想要的是:

I want to get name of institutes for which admissions (admission_open =1) are open in programs table.我想在程序表中获取招生(admission_open = 1)开放的机构名称。

How should I write query for that.do I have to join tables?我应该如何为那个编写查询。我必须加入表吗?

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

Now after you get object you can loop现在你得到对象后你可以循环

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

There are a lot of ways to do this.有很多方法可以做到这一点。 Like user @ujwal dhakal said or with joins, but I prefer this:就像用户@ujwal dhakal 所说的或加入的一样,但我更喜欢这个:

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

You can try你可以试试

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

OR或者

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

$programs will have Program objects with admission_open = 1 and institute data $programs 将有带有admission_open = 1 的Program 对象和机构数据

foreach($programs as $program){
       echo $program->institute->name;
}
$institutions = Institute:::whereHas('programs', function($query) {
                   $query->where('admission_open', '=',1);
                })->get();

Hope this helps希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM