staudenmeir / belongs-to-through

Laravel Eloquent BelongsToThrough relationships
MIT License
1.17k stars 91 forks source link

Incorrect relation when the model is new and is not saved #17

Closed brunogaspar closed 8 years ago

brunogaspar commented 8 years ago

Hello,

Didn't had the chance to look into a fix as of yet, maybe you know how to fix it more quickly heh

Here's the model i have

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Znck\Eloquent\Traits\BelongsToThrough;
use Illuminate\Database\Eloquent\SoftDeletes;

class CustomerEquipment extends Model
{
    use BelongsToThrough, SoftDeletes;

    public $table = 'customer_equipments';

    protected $fillable = [
        'customer_id',
        'serial_number',
        'manufacturer_model_id',
    ];

    public function manufacturer()
    {
        return $this->belongsToThrough(Manufacturer::class, ManufacturerModel::class);
    }
}

Note: Just removed some methods and docblocks that were not required.

If i do the following:

$equipment = new CustomerEquipment;

var_dump($equipment->manufacturer);

It returns a manufacturer object, which is wrong, it should return null since it's a fresh, not saved, model.

znck commented 8 years ago

@dannyweeks could you look into this? 😟 I am not free for next 2 weeks.

dannyweeks commented 8 years ago

@znck Pretty swamped at the moment too buddy but will look into as soon as I get a chance!

martintern commented 8 years ago

query uses where id = $this->id and when it is null it seems to return a random/last result. i wonder, why would $this->id be needed if you already have $this->intermediateModel_id