Thomas Shelby
Thomas Shelby

Reputation: 1370

Many to one on one table, relationship in laravel

I have model, named Magazine. This model represents of magazines table.

magazines
--id
--name

I also have model, named Transfer. This model is represents of transfers table. In this table I would like store information about product transfers.

transfers
--id
--source
--target

There are two important columns, source is id of magazine from I getting product, target is id of magazine where I put the product.

How should I create relationship in Eloquent model? I did something like this

public function source()
{
    return $this->belongsTo('Magazine', 'source');
}

public function target()
{
    return $this->belongsTo('Magazine', 'target');
}

But, doesn't work. If I call $transfer->source I only get id, which is stored in this column(integer value). But I would like get Magazine object. If I change method name from source() to magazine(), Eloquent returns Magazine object, and this is correct.

How should I create relationship if source and target indicate on the same table

Upvotes: 0

Views: 2698

Answers (2)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81157

Your fields and methods overlap. So now you can do this:

$transfer->source()->getResult()->name;

but obviously this is not the way to handle relationships.

That said, to make it work as expected, rename either methods or table fields. I suggest this:

table transfers: id, source_id, target_id

// Transfer model
public function source()
{
    return $this->belongsTo('Magazine', 'source_id');
}

public function target()
{
    return $this->belongsTo('Magazine', 'target_id');
}

Upvotes: 3

Pᴇʜ
Pᴇʜ

Reputation: 57683

If you call $transfer->source you will only get the id. You need to load your source too

$transfer = Transfer::with('source')->find(123);

and then access the name of the source

$nameOfSource = $transfer->source->name

Upvotes: 0

Related Questions