dongyin8009 2018-07-21 03:46
浏览 107
已采纳

Laravel Eloquent ORM:通过多个一对多的关系获得价值

I have three tables which are users, loans, statuses

The relationship is like this:

A user can have many loans. a loan has many status steps. in the statuses table I have a column called status, basically it telsl this step yes, no. pending sort of situation.

the table structure look like this:

users table
->id
->... 

loans table

->id
->... 
->user_id (it is the foreign key ->references('id')->on('users');

statuses table

->id
->...
->status  (can be "yes", "no", "pending")
->... 
->loan_id (it is the foreign key ->references('id')->on('loans');

the models look like this:

in the User model :

public function loans(){
    return $this->belongsToMany('App\Loan'); 
   }

in the Loan model:

 public function users(){
    return $this->belongsToMany('App\User'); 
   }  
  public function statuses(){
        return $this->hasMany('App\Status');
    }

in the Status model:

 public function loan(){
        return $this->belongsTo('App\Loan');
    }

My question is how to get the status yes number for each user. say I have five users, each user have multiple loans. each loan have, say 20 steps. but different loan many have different yes steps . I would like to use laravel eloquent ORM to get a array tell me each user get how many yes at certain time. So I would be able to loop through this array in my front end blade file to display users progress. thanks!

  • 写回答

2条回答 默认 最新

  • dsv73806 2018-07-21 15:03
    关注

    Laravel's Collection, which you get when you use Eloquent, is great for this kind of operation. Say you want to get the 'yes' statuses of one user:

    //yesStatuses is itself a Collection, but it can be used in a foreach like an array
    $yesStatuses = $user->loans
      ->map(function ($loan) {
        return $loan->statuses;
      })
      ->filter(function ($status) {
        return $status->status === 'yes';
      });
    
    //Number of statuses === 'yes'
    $yesStatuses->count();
    //If you need it as a regular array
    $yesStatuses->toArray();
    

    When you query your users table you should take care of loading your loans and statuses eagerly, otherwise you'll be performing many queries for this operation. Something like this:

    $users = App\User::with('loans.statuses')->get();
    

    More on this:

    Eloquent Collections

    Eager loading of Eloquent Models

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!