Laravel口才连接多表

时间:2019-04-16 02:52:24

标签: laravel eloquent

我的雄辩加入存在一些问题。 我有4个表格的关系

贷款表 /贷款

 loan_id | quantity | user_id
 1       |   4      |   1   .

详细贷款表 / Loandetails

 loandetail_id | loan_id | inventory_id
 1             | 1       | 4          .

库存表 /库存

inventory_id  | name_inventory
  4           | Keyboard     .

用户表 /用户

user_id  | Name
  1      | This is my name

我想要雄辩的查询结果

{
   'loan_id' => 1,
   'inventory' => 'keyboard',
   'user' => 'This is my name',
   'quantity' => 4
 }

3 个答案:

答案 0 :(得分:2)

您需要在模型中映射以下关系。

Loan.php

public function loanDetails()
{
    return $this->hasMany(LoanDetail::class);
}

public function user()
{
    return $this->belongsTo(User::class);
}

LoanDetails.php

public function inventory()
{
    return $this->belongsTo(Inventory::class);
}

public function loan()
{
    return $this->belongsTo(Loan::class);
}

您可以执行此操作以查询数据库中的数据,

$loan = Loan::with('loanDetails.user', 'loanDetails.inventory')->find(1);

然后获得您想要的结果,

return [
            'loan_id' => $loan->id,
            'inventory' => $loan->inventory, //this will return the full inventory object you can do  $loan->inventory->name_inventory to access attributes
            'user' => $loan->user->name,
            'quantity' => $loan->quantity 
        ]

答案 1 :(得分:0)

$data = DB::table('loan')
        ->select('loan.id as loan_id','invetoris.name_inventory as inventory','users.Name as users', 'loan.quantity' )
        ->join('loandetail', 'loandetail.loan_id', '=', 'loan.loan_id')
        ->join('inventoris', 'inventoris.inventory_id', '=', 'loandetail.inventory_id')->join('users', 'users.user_id', '=', 'loan.user_id')
        ->get()->toArray();



$info = [];
foreach($data as $key => $val) {
$info[] = [
'loan_id' => $val['loan_id'],
'inventory' => $val['inventory'],
'user' => $val['users'],
'quantity' => $val['quantity']
]; }

答案 2 :(得分:0)

  $data = DB::table('Loan')
    ->select('Loan.id as loan_id','Inventories.name_inventory as 
             inventory','Users.Name as users', 'Loan.quantity' )
    ->join('Loandetails', 'Loandetails.loan_id', '=', 'Loan.loan_id')
    ->join('Inventories', 'Inventories.inventory_id', '=', 
           'Loandetails.inventory_id')
    ->join('Users', 'Users.user_id', '=', 'Loan.user_id')
    ->get()->toArray();