Maicom Rodeghiero
Maicom Rodeghiero

Reputation: 17

Use foreign key id to get a foreign table name

I have some tables, all estate have an category_id, I put a foreign key to do the relationship, but won't work now, How can I list my estate with the equivalent category name

Category Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $table = 'categories';
    protected $fillable = ['name'];

    public function estate()
    {
        return $this->belongsTo('App\Estate');
    }

}

Estate Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Estate extends Model
{
    protected $table = 'estates';
    protected $fillable = ['categories_id'];

    public function category()
    {
        return $this->hasMany('App\Category');
    }

}

Create Estate table

        Schema::create('estates', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->timestamps();

            $table->string('name');
            $table->string('estate_photo')->nullable(true);
            $table->double('value');
            $table->integer('label_id');
        });

Create Category table


        Schema::create('categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->timestamps();
        });

Add category foreign key to estate

        Schema::table('estates', function (Blueprint $table) {
            $table->unsignedBigInteger('categories_id');
            $table->unsignedBigInteger('sub_categories_id');
            $table->foreign('categories_id')->references('id')->on('categories');
            $table->foreign('sub_categories_id')->references('id')->on('sub_categories');
        });

My object have not foreign key data to get $object->categories_id->name

Upvotes: 0

Views: 851

Answers (2)

Vincent Decaux
Vincent Decaux

Reputation: 10714

According to your models, you have to use :

// get all estates for the example
$estates = Estate::get();

foreach ($estates as $estate) {
    // use the name of the relation to get your category - first
    dump($etate->category[0]->name);

    // or to get all categories
    foreach ($etate->category as $category) {
        dump($category->name);
    }
}

Upvotes: 1

Lotfi
Lotfi

Reputation: 320

I'm sure this would work .. correct me if I'm wrong

Estate::with('category')->get();

It will bring back all the estates, each one with its categories attached.

Upvotes: 1

Related Questions