【问题标题】:Some records (not all!) return null from Laravel eloquent relationship一些记录(不是全部!)从 Laravel 雄辩的关系中返回 null
【发布时间】:2021-10-28 00:06:39
【问题描述】:

我很绝望。这是关于这种模型关系的:

   public function customer()
    {
        return $this->hasOne('App\Models\InvoiceCustomer', 'invoice_id', 'id');
    }

当我执行查询时,我得到三个结果。两个与 InvoiceCustomer 模型的正确关系,但一个结果总是 customer: null

Invoice::whereHas(['customer'])->get();

invoice.id 字段值与数据库中的 invoice_customers.id 完全一致。

这是两个表的db架构:

数据库:invoice_customers

Schema::create('invoice_customers', function (Blueprint $table) {
            $table->foreignUuid('invoice_id')->references('id')->on('invoices')->cascadeOnDelete();
            $table->string('number');
            $table->string('salutation');
            $table->string('first_name');
            $table->string('last_name');
            $table->string('street');
            $table->string('house_number');
            $table->string('postcode');
            $table->string('city');
            $table->string('email');
            $table->timestamps();
        });

数据库:发票

Schema::create('invoices', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->foreignUuid('company_id')->references('id')->on('companies')->cascadeOnDelete();
            $table->string('number');
            $table->string('status');
            $table->timestamp('date');
            $table->decimal('total');
            $table->string('type');
            $table->json('additional_data')->default('{}');
            $table->timestamps();
        });

我希望有人有一个想法,或者以前可能有过这样的问题。

我很感激每一个答案。如果您还需要什么,请告诉我。非常感谢!

【问题讨论】:

    标签: php laravel eloquent relationship


    【解决方案1】:

    whereHas 接受第一个参数为 string 而不是 array 所以

    Invoice::whereHas('customer',function($query){
    
    })->get();
    

    由于你在关系中没有任何条件,所以你可以使用 has

    Invoice::whereHas('customer')->get();
    

    Invoice::has('customer')->get();
    

    在你的情况下更好的选择是has()

    参考:

      /**
         * Add a relationship count / exists condition to the query with where clauses.
         *
         * @param  string  $relation
         * @param  \Closure|null  $callback
         * @param  string  $operator
         * @param  int  $count
         * @return \Illuminate\Database\Eloquent\Builder|static
         */
        public function whereHas($relation, Closure $callback = null, $operator = '>=', $count = 1)
        {
            return $this->has($relation, $operator, $count, 'and', $callback);
        }
    

    【讨论】:

    • 对不起!谢谢您的回答!我尝试了一些东西并替换它。我最初使用with('customer'),但不幸的是它也无法使用。
    • @user16327873 那么你必须使用 Invoice::with('customer')->has('customer')->get();所以它只返回那些有客户的发票
    猜你喜欢
    • 2018-04-11
    • 2017-07-29
    • 2014-10-23
    • 2020-02-18
    • 2015-12-17
    • 2018-06-19
    • 2018-03-09
    • 2022-01-12
    • 2021-06-20
    相关资源
    最近更新 更多