laravel eloquent JOIN ON多个条件

时间:2015-03-15 16:18:59

标签: php mysql laravel join laravel-4

我有一个表格银行,它存储国家银行名称,代码等

我有一个表格 site_banks ,它存储银行帐户,银行持有人姓名和外国 bank_id ,其中包含银行

我有一个表格 deposit_records ,它存储存款时间,存款收据,状态等,以及外国 bank_id ,其中包含 site_banks < / p>

deposit_records ,状态字段,值1表示成功

现在我想计算每个 site_banks

的总收入

但我不希望每一行 site_banks 调用一个查询来计算,这将有很多sql查询调用

所以我想我可以使用加入,下面是 site_banks 模型文件, scopeGroupAllSiteBanksByBranch 是我要收集所有site_banks的地方,与SUM连接,返回数组

但即使我有大约200个 site_banks 行,还有很多 deposit_records status ='1' ,但 scopeGroupAllSiteBanksByBranch 总是只返回一行,我不明白为什么,我复制sql查询在mysql中运行,结果相同,只返回1行。

<?php

use Illuminate\Database\Eloquent\SoftDeletingTrait;

class SiteBanks extends \LaravelBook\Ardent\Ardent {

    use SoftDeletingTrait;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'site_banks';

    protected $dates = ['deleted_at'];

    protected $fillable = array('bank_id', 'bank_name', 'bank_account', 'bank_holder', 'bank_username', 'bank_password', 'min_deposit', 'max_deposit', 'daily_max_deposit');

    public static $rules = array(
        'bank_id' => 'required|exists:banks,id',
        'bank_name' => 'required|min:1',
        'bank_account' => 'required|min:1|numberonly',
        'bank_holder' => 'required|min:1',
        'bank_username' => 'required|min:1',
        'bank_password' => 'required|min:1',
        'min_deposit' => 'required|fund',
        'max_deposit' => 'required|fund',
        'daily_max_deposit' => 'required|fund',
    );

    public function bank() {
        return $this->belongsTo('Banks', 'bank_id');
    }

    public function transactions() {
        return $this->hasMany('Deposit', 'bank_id', 'id');
    }

    public function transactionsDone() {
        return $this->hasMany('Deposit', 'bank_id', 'id')->where('status', '=', 1);
    }

    public function transactionsBanned() {
        return $this->hasMany('Deposit', 'bank_id', 'id')->where('status', '=', 2);
    }

    public function transactionsPending() {
        return $this->hasMany('Deposit', 'bank_id', 'id')->where('status', '=', 0);
    }

    public function setBankPasswordAttribute($value) {
        $this->attributes['bank_password'] = Crypt::encrypt($value);
    }

    public function getBankPasswordAttribute() {
        return Crypt::decrypt($this->attributes['bank_password']);
    }

    public function scopeGetAvailableBanks($query) {
        $query->where(DB::raw("(current_deposit < daily_max_deposit) OR (current_deposit IS NULL) OR (DATE(last_deposit) != DATE(NOW()) OR last_deposit IS NULL) OR (DATE(last_deposit) = DATE(NOW()) && current_deposit < daily_max_deposit)"));
        $query->groupBy('bank_id')->orderBy('id', 'ASC');
    }

    public function scopeGroupAllSiteBanksByBranch($query) {
        $bank = \SiteBanks::withTrashed()
            ->leftJoin('deposit_records', function($q) {
                $q->on('deposit_records.bank_id', '=', 'site_banks.id');
                $q->where('deposit_records.status', '=', 1, 'and');
            })
            ->select(array('site_banks.*', DB::raw('SUM(`deposit_records`.`deposit_amount`) AS `total_income`')))
            ->get();
//        $bank = \SiteBanks::withTrashed()->get();
        $bank->load('bank');

        $banks = array();
        foreach($bank as $key => $var) {
            $arr = array();

            $arr = $var->toArray();
            $arr['income'] = $var->total_income;
            $banks[$var->bank->bank_name][] = $arr;
        }

        return $banks;
    }

}

SQL查询

  

选择site_banks。*,SUM(deposit_recordsdeposit_amount)AS   来自total_income的{​​{1}}已离开加入site_banks   deposit_recordsdeposit_records = bank_idsite_banks和   iddeposit_records ='1'

scopeGroupAllBanksByBranch

的结果

var_dump

status

3 个答案:

答案 0 :(得分:5)

您可以按照以下代码解决问题

SQL查询

LEFT JOIN bookings  
           ON rooms.id = bookings.room_type_id AND (bookings.arrival = ? OR bookings.departure = ? )

Laravel加入多个条件

 ->join('bookings', function($join) use ($key1, $key2)
{
    $join->on('rooms.id', '=', 'bookings.room_type_id');
    $join->on(function($query) use ($key1, $key2)
            {
             $query->on('bookings.arrival', '=', $key1);
             $query->orOn('departure', '=',$key2);
            });

})

答案 1 :(得分:3)

public function scopeGroupAllSiteBanksByBranch($query) {
        $bank = \SiteBanks::withTrashed()
            ->leftJoin('deposit_records', function($q) {
                $q->on('deposit_records.bank_id', '=', 'site_banks.id');
                $q->where('deposit_records.status', '=', 1, 'and');
            })
            ->select(array('site_banks.*', DB::raw('SUM(`deposit_records`.`deposit_amount`) AS `total_income`')))
            ->groupBy('site_banks.id')
            ->get();

我找到了解决方案, groupBy('site_banks.id')然后全部设定。

答案 2 :(得分:1)

这是解决方案。您可以加入多个条件。

$query = self::select('websites.id','websites.website_url','cron_tracking_details.cron_type');
    $query = $query->leftJoin('cron_tracking_details',function ($join){
        $join->on(function ($queryone){
            $queryone->on('websites.id','=','cron_tracking_details.website_id');
            $queryone->where('cron_tracking_details.cron_type','=',"sitemap_create");
            $queryone->Where('cron_tracking_details.cron_date','<','2020-11-19');
        });
    });
    $query = $query->orderBy('cron_tracking_details.id','desc');
    $query = $query->limit(1);
    return $query = $query->get();

这段代码将像这样准备查询。

select `websites`.`id`, `websites`.`website_url`, `cron_tracking_details`.`cron_type` from `websites` left join `cron_tracking_details` on (`websites`.`id` = `cron_tracking_details`.`website_id` and `cron_tracking_details`.`cron_type` = ? and `cron_tracking_details`.`cron_date` < ?) order by `cron_tracking_details`.`id` desc limit 1