【问题标题】:Why is my Eloquent Relation not filling all of my objects?为什么我的 Eloquent Relation 没有填满我的所有对象?
【发布时间】:2021-12-28 11:19:12
【问题描述】:

我有一个仅包含 ID 和名称的“类型”表,该关系适用于第一个对象,但在以下对象上返回 null。这是我的 JSON 的样子:

{"id":1,"type_id":1,"name":"test1","enabled":1,"measurement_type":{"id":1,"name":"test"}},
{"id":2,"type_id":2,"name":"test2","enabled":0,"measurement_type":null}]},
{"id":3,"type_id":1,"name":"test3","enabled":1,"measurement_type":null}]}

这是我的关系:
测量字段模型

    public function measurement_type() {
        return $this->belongsTo(MeasurementType::class, 'type_id');
    }

MeasurementTypes 模型

    public function measurement_type() {
        return $this->belongsTo(MeasurementData::class); 
    }

在这个模型中,我已经有一个measurement_field 函数,它为MeasurementData(不同的模型)声明了一个belongsTo 那么,如何使用hasMany 为类型命名新函数?

我的控制器:

    public function index()
    {
        return JsonResource::collection(MeasurementField::with('measurement_type')->get());
    }

它们都包含数据,正如您从 JSON 中看到的那样,关系对它没有任何作用。

我的迁移:

        Schema::create('measurement_types', function (Blueprint $table) {
            $table->id()->autoincrement();
            $table->string('name');
        });
        Schema::create('measurement_fields', function (Blueprint $table) {
            $table->id()->autoincrement();
            $table->foreignId('type_id')->constrained('measurement_types');
            $table->string('name')->unique();
            $table->boolean('enabled');
        });

【问题讨论】:

  • 你试过我的解决方案了吗?

标签: sql laravel eloquent


【解决方案1】:

我认为你的measurement_type 有很多measurement_field

我猜你必须把它放在你的 MeasurementField 模型中:

public function measurement_type() {
        return $this->belongsTo(MeasurementType::class, 'type_id');
    }

【讨论】:

  • 我把它变成了一个 hasMany 但我得到了这个作为响应:SQLSTATE [42S22]:找不到列:1054 'where 子句'中的未知列'measurement_types.type_id'(SQL:select * from measurement_types 其中measurement_types.type_id 在 (1, 2, 3)))
  • 我将我的问题编辑为我现在如何拥有我的代码。
  • MeasurementFields 模型应该有measurement_type函数
  • MeasurementType模型应该有measurement_field函数
  • 我添加了架构,你还想要我的其他模型吗?
猜你喜欢
  • 2020-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多