简体   繁体   English

PHP/Laravel: SELECT 和 JOIN 两个表

[英]PHP/Laravel: SELECT and JOIN two tables

I have three tables as shown below and trying to join the expenses and allowance table on customers.我有如下所示的三个表,并试图加入客户的费用和津贴表。 I have tried using the code below but it returns null on expenses and allowances.我试过使用下面的代码,但它返回 null 的费用和津贴。 I tried inner JOIN as well but didn't work.我也尝试过 inner JOIN 但没有用。

I have tables as below:我有如下表格:

customers(id, user_id, full_name)
expenses(id, customer_id, name, amount)
allowances(id, customer_id, name, quantity)

And i tried using the code below but doesn't work.我尝试使用下面的代码但不起作用。

$logs = Customer::query()
     ->select([
            "customers.id",
            "customers.full_name",
            "expenses.name as expenses_name",
            "expenses.amount as expenses_amount",
            "allowances.name as allowance_name",
            "allowances.quantity as allowance_quantity"
     ])
     ->join('expenses', function (JoinClause $join) {
                $join->type = 'left outer';
                $join->on('expenses.customer_id', 'customers.id');
     })
     ->join('allowances', function (JoinClause $join) {
                $join->type = 'left outer';
                $join->on('allowances.customer_id', 'customers.id');
     });

return $logs->toJson();

I want output as:我想要 output 作为:

{
id:'',
full_name:'',
expenses:{{expenses_name, expenses_amount},{expenses_name, expenses_amount}},
allowances:{{allowance_name, allowance_quantity},{allowance_name, allowance_quantity}}
}

You can also use eloquent relationship.您也可以使用 eloquent 关系。

define relations in Customer Model在客户 Model 中定义关系

public function expenses()
{
    return $this->hasMany(Expense::class);
}

public function allowances()
{
    return $this->hasMany(Allowance::class);
}

get Customers with relationship获得有关系的客户

$logs = Customer::with(['expenses','allowances'])->get();

Use the following Code:使用以下代码:

$logs = Customer::select([
    "customers.id",
    "customers.full_name",
    "expenses.name as expenses_name",
    "expenses.amount as expenses_amount",
    "allowances.name as allowance_name",
    "allowances.quantity as allowance_quantity"
])
->leftjoin('expenses', 'customers.id','=','expenses.customer_id')
->leftjoin( 'allowances','customers.id','=','allowances.customer_id')
->get();

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

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