Laravel Eloquent - Select 所有列加上仅使用 Eloquent 的子查询
Laravel Eloquent - Select all columns plus a subquery using Eloquent only
我需要 select 来自 table 的所有列和使用 laravel 的 eloquent 中的子查询的附加列。例如,
SELECT *, (SELECT COUNT(*) FROM transactions WHERE transactions.customer=customers.id) AS transactions FROM customers
现在,我想出了使用 selectRaw
的原始查询,例如:
$customers = Customer::selectRaw('*, (SELECT COUNT(*) FROM transactions WHERE transactions.customer=customers.id) AS transactions')->get();
但我想以 eloquent 的方式进行,而不使用原始查询。
正如我在这里看到的那样,您在客户和交易之间有 1-N 关系,如果您已经使用 eloquent 关系 belongTo 和 hasMany 设置了模型,那么您可以使用 With 进行预加载子查询:
Eloquent 预加载和预加载计数关系
//customers + transactions for each one
$customers = Customer:with('transactions')->get();
// customers + transaction count for each one
$customers = Customer:withCount('transactions')->get();
客户模型
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
/**
* Get the transactions for the customer.
*/
public function transactions()
{
return $this->hasMany(Transaction::class);
}
}
交易模型
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Transaction extends Model
{
/**
* Get the customer of this transaction.
*/
public function customer()
{
return $this->belongsTo(Customer::class);
}
}
我需要 select 来自 table 的所有列和使用 laravel 的 eloquent 中的子查询的附加列。例如,
SELECT *, (SELECT COUNT(*) FROM transactions WHERE transactions.customer=customers.id) AS transactions FROM customers
现在,我想出了使用 selectRaw
的原始查询,例如:
$customers = Customer::selectRaw('*, (SELECT COUNT(*) FROM transactions WHERE transactions.customer=customers.id) AS transactions')->get();
但我想以 eloquent 的方式进行,而不使用原始查询。
正如我在这里看到的那样,您在客户和交易之间有 1-N 关系,如果您已经使用 eloquent 关系 belongTo 和 hasMany 设置了模型,那么您可以使用 With 进行预加载子查询:
Eloquent 预加载和预加载计数关系
//customers + transactions for each one
$customers = Customer:with('transactions')->get();
// customers + transaction count for each one
$customers = Customer:withCount('transactions')->get();
客户模型
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
/**
* Get the transactions for the customer.
*/
public function transactions()
{
return $this->hasMany(Transaction::class);
}
}
交易模型
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Transaction extends Model
{
/**
* Get the customer of this transaction.
*/
public function customer()
{
return $this->belongsTo(Customer::class);
}
}