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

loans table

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

statuses table

->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'
    //If you need it as a regular array

    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

    解决 无用
    打赏 举报

相关推荐 更多相似问题