Home > OS >  laravel How to get the table's column value in model and re-use in where
laravel How to get the table's column value in model and re-use in where

Time:08-24

There are three tables:

  1. sys_session: id, oid, ... and other columns
  2. user: id, ...
  3. member: id,...

sys_session's oid means both user_id(negative) or member_id(positive).

If oid = 5, it's positive number, so it means member_id = 5
If oid = -5, it's negative number, so it means user_id = 5

How to define the user() relationship?

class SysSession extends Model
{
    public function member()
    {
        return $this->hasOne(\App\Models\Member::class, 'id', 'oid');
    }

    public function user()
    {
        return $this->hasOne(\App\Models\Member::class, 'id', 'oid')
                    ->where('oid', abs(xxx));
    }
}

What should I write in user's where() ?

CodePudding user response:

try this:

    public function member()
    {
        return $this->belongsTo(\App\Models\Member::class, 'oid', 'id')
                    ->where('oid', '>', 0);
    }

    public function user()
    {
        return $this->belongsTo(\App\Models\Member::class, 'oid', 'id')
                    ->where('oid', '<', 0);
    }

CodePudding user response:

The solution is $this->oid. a simple anwser.

public function user()
{
    return $this->hasOne(\App\Models\Member::class, 'id', 'oid')
                ->where('id', abs($this->oid));
}
  • Related