Laravel Eloquent - 仅使用 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();

但我想在不使用原始查询的情况下以雄辩的方式做到这一点。

海仁赫克

正如我在这里看到的,您在 customer 和 transaction 之间有 1-N 关系,如果您已经设置了具有说服力关系的模型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);
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章