Php 具有多个where的Laravel查询未返回预期结果
我正试图在一个包含2个where子句的模型中从存储库构建一个查询 这是我在MySql表中的数据:Php 具有多个where的Laravel查询未返回预期结果,php,laravel,Php,Laravel,我正试图在一个包含2个where子句的模型中从存储库构建一个查询 这是我在MySql表中的数据: id name environment_hash 1 online_debit abc 2 credit_cart abc 我想按名称和环境进行查询。为此,我创建了findByHashAndMethod()方法(见下文) 但当我在控制器中使用它时,如下所示: $online_debit = $this->ecommerce
id name environment_hash
1 online_debit abc
2 credit_cart abc
我想按名称和环境进行查询。为此,我创建了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');
}
}
虽然我不能完全确定为什么->first()
会返回多个结果,但您的存储库方法存在一些容易出错的突出问题
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;
}
}
虽然我不能完全确定为什么->first()
会返回多个结果,但您的存储库方法存在一些容易出错的突出问题
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;
}
}
返回时尝试添加->获取(),方法中将$this->model与$model混合。返回时尝试添加->获取(),方法中将$this->model与$model混合。