【问题标题】:Laravel Eloquent retrieve specific informationLaravel Eloquent 检索特定信息
【发布时间】:2016-06-23 17:43:46
【问题描述】:

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

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

机构

 id    |name   | user_id 

 1     |abc    |22       
 2     |xyz    |32        

现在 Institute2 (xyz) 有以下项目

程序

 id     |institute_id| name | admission_open|

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

Institute.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) 的机构的名称。

我应该如何为此编写查询。我必须加入表吗?

【问题讨论】:

    标签: php mysql database laravel eloquent


    【解决方案1】:
    $tests = Programs::where('admission','1')->get();
    

    现在你得到对象后就可以循环了

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

    【讨论】:

    • $tests 返回数据正常。但是$test->institute->name; 抛出错误`尝试获取非对象的属性`
    • 这意味着你还没有设置你的迁移位置
    【解决方案2】:

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

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

    【讨论】:

    • 收到错误call to undefined method Illuminate\Database\Query\Builder::program()
    • 好吧,我试过这个并得到空数组[]:` $list =Institute::whereHas('programs', function($query) { $query->where('admission_open', '=',1); })->get(); echo json_encode($list);`
    • @Nomi 你能提供数据库的转储吗?例如将其存储到 pastebin.com ?
    【解决方案3】:
    $institutions = Institute:::whereHas('programs', function($query) {
                       $query->where('admission_open', '=',1);
                    })->get();
    

    希望对你有帮助

    【讨论】:

    • 获取空数组[]
    【解决方案4】:

    你可以试试

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

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

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

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

    【讨论】:

    • 在这两种情况下我都得到了研究所的空值这是我的 json [{"id":237,"name":"BS Software","admission_open":1,"created_at":"2016-03-08 18:06:39","updated_at":"2016-03-08 18:06:39","institute_id":21,"institute":null}
    • 您在机构表中是否有 id 21 的表中的任何数据 :: 这个 id 我可以在您的输出中看到
    • 感谢问题已解决。我遇到了数据库关系问题。
    猜你喜欢
    • 2021-10-01
    • 2014-04-11
    • 1970-01-01
    • 1970-01-01
    • 2013-01-30
    • 1970-01-01
    • 2017-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多