I have a "types" table which contains only ID and Name, the relation works on the first object but returns null
on the following objects. Here is what my JSON looks like:
{"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}]}
Here are my relations:
MeasurementFields Model
public function measurement_type() {
return $this->belongsTo(MeasurementType::class, 'type_id');
}
MeasurementTypes Model
public function measurement_type() {
return $this->belongsTo(MeasurementData::class);
}
In this Model I already have a measurement_field function which declares a belongsTo to MeasurementData (different Model) So, how do I name the new function with hasMany for types?
My Controller:
public function index()
{
return JsonResource::collection(MeasurementField::with('measurement_type')->get());
}
They all contain data, as you can see from the JSON, the relation just doesn't do anything with it.
My migrations:
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');
});
CodePudding user response:
I think your measurement_type
has many measurement_field
.
and I guess you have to put this in your MeasurementField
Model:
public function measurement_type() {
return $this->belongsTo(MeasurementType::class, 'type_id');
}