我需要使用子查询从表中选择所有列和其他列。例如,
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();
但我想在不使用原始查询的情况下以雄辩的方式做到这一点。
正如我在这里看到的,您在 customer 和 transaction 之间有 1-N 关系,如果您已经设置了具有说服力关系的模型belongTo 和 hasMany,那么您可以使用 With 进行急切加载子查询:
//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);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句