Support the ongoing development of Laravel.io →
Database Eloquent

SOLVED My mistake, I mixed up the model relationships :)

Hi guys,

I'm new Eloquent (usually use raw queries) and I get the whole concept of how relationships inside it work, and weirdly enough I had no issues with something more complex, including pivot tables etc, however, I cannot make this current thing work.

Simplified...

I have several persons (in "persons"), and each person should have one category. Those categories are in a second table ("categories") and every person can only have one of those at a time.

Table "persons"

id_person | Integer (Unsigned)

id_category | Integer (Unsigned)

Table "categories"

id_category | Integer (Unsigned)

name | Varchar (25)

I also do have two models, one for "Category" and one for "Person" which I connect with belongsTo and hasOne, respectively.

<b>Person Model</b>

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Person extends Model {

    protected $primaryKey = 'id_person';
    protected $table = 'persons';

    public function category() {
        return $this->hasOne('App\Models\Category', 'id_category', 'id_category');
    }
}

<b>Category Model</b>

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Category extends Model {

    /**
     * @var string
     */
    protected $primaryKey = 'id_category';

    /**
     * @var string
     */
    protected $table = 'categories';

    public function person() {
        return $this->belongsTo('App\Models\Person', 'id_category', 'id_category');
    }
}

Any help would be greatly appreciated!

Thanks!

Last updated 3 years ago.
0

Please what error did you get, could you put that here. Thanks

0

Sign in to participate in this thread!

PHPverse

Your banner here too?

codestic codestic Joined 19 Nov 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.