简体   繁体   English

Laravel 5与刀片中查询的模型关系

[英]Laravel 5 Model Relation to Query in blade

Schema User Table 模式用户

ID|NAME
1 |John
2 |Doe

Schema Financial Table 架构财务

ID|USER_ID|PROFIT |DATE
1 |1      |1000   |2016-12-22
2 |2      |-2000  |2016-12-22
3 |1      |2000   |2016-12-24
4 |2      |-2000  |2016-12-24

User Model 用户模型

class User extends Model
{
    public function Financial()
    {
        return $this->hasMany('App\Financial');
    }
}

Financial Model 财务模型

class Financial extends Model
    {
        public function financial()
        {
            return $this->belongsTo('App\User');
        }
    }

My Controller 我的控制器

class MyController extends Controller
{
    public function index()
    {
        $user = User::get();
        $financial = Financial::get();
        return view('page.index',compact('user','financial'));
    }
}

My Blade 我的剑

@foreach ($user as $u)
    <tr>
        <td>{{$u->id}}</td>
        <td>
             {{$u->financial->sum('gross')}}
             {{-- Above code doesn't work --}}
             {{-- Run something link --}}
             {{select (sum(profit) as total) from financial where user_id = $u->id}}
        </td>
    </tr>
@endforeach

QUESTION

How can i achieve that select from my blade? 我如何才能从刀片中实现这一选择 i'm planning to use @inject('DB','Illuminate\\Support\\Facades\\DB') so i can use DB::raw in my blade, but i'm confused on how to execute the query to achieve the select :( 我打算使用@inject('DB','Illuminate \\ Support \\ Facades \\ DB'),因此可以在刀片中使用DB :: raw ,但是我对如何执行查询以实现选择感到困惑:(

Solved by using Laravel Collection Method Pluck and Laravel Blade Service Injection .Below is the code i've done to archive what i want: 通过使用Laravel收集方法PluckLaravel刀片服务注入解决。以下是我完成的存档所需代码:

@inject('financial','App\Financial') {{-- inject before foreach --}}
@foreach ($user as $u)
    <tr>
        <td>{{$u->id}}</td>
        <td>{{$financial->where('user_id','=',$u->id)->get()->pluck('profit')->sum()}}</td>
    </tr>
@endforeach

To Evaluate what happen: 要评估发生了什么:

$financial->where('user_id','=',$u->id)->pluck('profit')->sum()
//   get financial where user_id = $u->id   // get the profit // sum the profit 

Cheers! 干杯!

You could have simply done this: 您可以简单地做到这一点:

{{$u->financial()->sum('gross')}}

If you are running a query on a relationship, add function brackets while calling it. 如果要在关系上运行查询,请在调用它时添加功能括号。

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

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