Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Jelly's avatar
Level 1

HasOne relation returns wrong record

So I have the following table structure

Storage Table Storage

Article Table Article

Stock Table Stock

My relations are defined as the following

class Article extends Model
{
    protected $table = 'article';
    protected $primaryKey = 'A_ID';
    public $timestamps = false;

    public function stock()
    {
        return $this->hasMany('App\Stock','A_ID');
    }
}
class Storage extends Model
{
    protected $table = 'storage';
    protected $primaryKey = 'S_ID';
    public $timestamps = false;

    public function business()
    {
        return $this->belongsTo('App\Business','B_ID');
    }
    public function stock()
    {
        return $this->hasMany('App\Stock','S_ID');
    }
}

class Stock extends Model
{
    protected $table = 'stock';
    protected $primaryKey = 'STO_ID';
    public $timestamps = false;

    public function storage()
    {
        return $this->belongsTo('App\Storage','S_ID');
    }
    public function article()
    {
        return $this->hasOne('App\Article','A_ID');
    }
    public function movement()
    {
        return $this->hasMany('App\StockMovement','STO_ID');
    }
}

My problem is when i select the stock with the STO_ID = 2 and then access the article via $stock->article it returns the record for Metall even though the saved A_ID of 1 is Wood This only occurs to the second stock. The first stock with the id = 1 returns wood

0 likes
3 replies
nhaley's avatar

What does it do if you add the local key to hasOne:

return $this->hasOne('App\Article', 'A_ID', 'A_ID');

nhaley's avatar

It also looks like a belongsTo. Like with a post/thread belonging to a channel, a good example is on Jeffrey's Council project at:

https://github.com/JeffreyWay/council/blob/master/app/Thread.php

It looks to me like the hasOne is intended for one-one, user->profile where a user has one profile and a profile has one user.

For your stocks and articles you have articles having many stocks which you define correctly with hasMany in Articles but, the inverse, as I understand it, for that is a belongsTo and not a hasOne.

Best of luck.

Please or to participate in this conversation.