Laravel查询多个不返回预期结果的查询

时间:2016-10-17 10:21:35

标签: php laravel

我试图从具有2 where子句的模型中的存储库构建查询。

这是我在MySql表中的数据:

id      name            environment_hash
1       online_debit    abc
2       credit_cart     abc

我想按名称和environment_hash进行查询。为此,我创建了方法findByHashAndMethod()(见下文)。

但是当我在我的控制器中使用它时,就像这样:

$online_debit = $this->ecommercePaymentMethodRepository->findByHashAndMethod($hash, 'online_debit')->first();

或者这个:

$credit_card = $this->ecommercePaymentMethodRepository->findByHashAndMethod($hash, 'credit_cart')->first();

我不断获取两行,而不仅仅是过滤的行。代码有什么问题?

这是我的PaymentMethodRepository.php

class EcommercePaymentMethodRepository extends BaseRepository
{


    public function findByHashAndMethod($hash = null, $payment_method)
    {
        $model = $this->model;

        if($hash) 
        {
            $filters = ['environment_hash' => $hash, 'name' => $payment_method];
            $this->model->where($filters);
        }

        else
        {
            $this->model->where('environment_hash',  Auth::user()->environment_hash)
                        ->where('name', $payment_method);
        }


        return $model;
    }

    public function model()
    {
        return EcommercePaymentMethod::class;
    }
}

这是我的模型EcommercePaymentMethod.php

<?php

namespace App\Models;
use Eloquent as Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class EcommercePaymentMethod extends Model
{
    use SoftDeletes;

    public $table = "ecommerce_payment_methods";

    protected $dates = ['deleted_at'];

    public $fillable = [
        "name",
        "payment_processor_id",
        "active",
        "environment_hash"
    ];

    protected $casts = [
        "name" => "string"
    ];

    public function payment_processor()
    {
        return $this->hasOne('App\Models\EcommercePaymentProcessor');
    }
}

1 个答案:

答案 0 :(得分:2)

虽然我不完全确定为什么->first()会返回多个结果,但您的Repository方法有一些明显容易出错的明显问题。

class EcommercePaymentMethodRepository extends BaseRepository
{

    // 1. Do not put optional parameter BEFORE non-optional
    public function findByHashAndMethod($payment_method, $hash = null)
    {
        // 2. Call ->model() method
        $model = new $this->model();

        // 3. Logic cleanup
        if (is_null($hash)) {
            $hash = Auth::user()->environment_hash;
        }

        return $model->where('environment_hash', $hash)
            ->where('name', $payment_method);
    }

    public function model()
    {
        return EcommercePaymentMethod::class;
    }
}