laraveleloquententity-relationshiphas-manybelongs-to

Relationships laravel doesn't work after 5th position


I have 2 models:

model 1 -> hasMany(model2)

public function model2(){
    return $this->hasMany(Model2::class, 'field_fk_id');
}

model 2 -> belongsTo(model1)

public function model1(){
        return $this->belongsTo(Model1::class,'id');
    }

When i try to get the relationship of 5 first elements of model 2, work well. When i try to get the 6th or highest id, return null.

Example: Ok reference

"status": true,
    "message": "Model 2",
    "data": {
        "id": 4,
        "name": "Name example",
        "field_fk_id": 1,
        "created_at": "2023-04-04T09:23:41.000000Z",
        "updated_at": "2023-04-04T09:23:41.000000Z",
        "model1": {
            "id": 2,
            "name": "Name parent example",
            "created_at": "2023-04-04T09:23:41.000000Z",
            "updated_at": "2023-04-04T09:23:41.000000Z"
        }
    }

Wrong reference:

"status": true,
        "message": "Model 2",
        "data": {
            "id": 11,
            "name": "Name example 11",
            "field_fk_id": 3,
            "created_at": "2023-04-04T09:23:41.000000Z",
            "updated_at": "2023-04-04T09:23:41.000000Z",
            "model1": null
        }

When i try to get the relationship since model 1, the relation hasMany work well. Return all the referencies.

Any idea for fix this?

P.S.: the references of field_fk_id exists, i check it at the request and i check it at the database.


Solution

  • The second parameter of belongsTo is a foreign key. So it should be:

    public function model1(){
       return $this->belongsTo(Model1::class,'field_fk_id');
    }