【问题标题】:Laravel Eloquent - Select all columns plus a subquery using Eloquent onlyLaravel Eloquent - 仅使用 Eloquent 选择所有列和子查询
【发布时间】:2021-05-11 10:13:04
【问题描述】:

我需要在 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();

但我想以雄辩的方式进行,而不使用原始查询。

【问题讨论】:

    标签: laravel-5 eloquent


    【解决方案1】:

    正如我在这里看到的,您在客户和交易之间有 1-N 关系,如果您已经设置了具有雄辩关系的模型 belongsTo 和 hasMany ,那么您可以使用 With 进行急切加载子查询:

    Eloquent Eager load 和 Eager load 计数关系

    //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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-08
      • 2017-11-23
      • 2020-09-12
      • 1970-01-01
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      • 2018-11-19
      • 1970-01-01
      相关资源
      最近更新 更多