Jeremy
Jeremy

Reputation: 1962

Bug with my relation HasMany/BelongsTo

I have a model Work with this relation

public function types()
{
    return $this->belongsTo('App\Models\Type');
}

And a model Type with this relation

public function works()
{
    return $this->hasMany('App\Models\Work');
}

I try to access in my view show view to type but I've a lot of errors

Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$name

I try this : $work->types()->name for get data.

In my DB, my table 'Works' have a foreignkey 'type_id'.

I would like to get the 'type' of the post. There can be only one per post.

Thank you very much !

Upvotes: 0

Views: 42

Answers (3)

user6491909
user6491909

Reputation:

Since you are not using default id as foreign key you should add

protected $primaryKey = "type_id";

in your model

Upvotes: 0

ambrooo
ambrooo

Reputation: 144

You should have on Work Model:

public function type()
{
    return $this->belongsTo('App\Models\Type');
}

and on your view:

$work->type->name;

Upvotes: 2

Spholt
Spholt

Reputation: 4042

Semantically you want to make your relationships like so:

Work

// A work is of a single type
public function type()
{
    return $this->belongsTo('App\Models\Type');
}

Type

// A type of work can have many items of work
public function works()
{
    return $this->hasMany('App\Models\Work');
}

You can then access the relationship like so:

$type = Work::first()->type // return object of type Type
$works = Type::first()->works // return collection of objects of type Work

EDIT

By accessing the relationship with () you are returning the underlying query builder instance of the relationship and you will need to finish your statement with ->get() like so:

$works = Type::first()->works()->get();

Upvotes: 4

Related Questions