通过一种模式建立关系

时间:2020-03-10 15:11:18

标签: laravel

我有三个表-用户,属性和设备。

users
 id
 name

properties
 id
 name
 user_id

devices
 id
 name
 property_id

如何从设备模型定义与用户模型的直接关系?

class Device extends Model
{
    public function user()
    {
        return $this->....();
    }
}

是否可以定义这种关系?谢谢。

3 个答案:

答案 0 :(得分:2)

确保在其他类中设置所有关系。

class Property extends Model
{
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}
class Device extends Model
{
    public function property()
    {
        return $this->belongsTo('App\Property');
    }

    public function user()
    {
        return $this->belongsTo('App\User', null, null, 'property');
    }
}

您可以在belongsTo方法的第4个参数中提供一个关系。

答案 1 :(得分:0)

   //user model
    public function role()
    {
        return $this->belongsTo('App\Role');
    }
    public function employee()
    {
        return $this->hasMany('App\Employee');
    }
   //role model
    public function users()
    {
        return $this->hasMany('App\User');
    }
    //employee model
    public function users()
    {
        return $this->belongsTo('App\User');
    }
    //value show using tinker command in command promote
     App\User::find(1)->employee;
     App\User::find(1)->role;

答案 2 :(得分:0)

我想我找到了解决方案,这就是我最终要解决的问题。

class Device extends Model
{
    public function user()
    {
        $instance = new User();
        $instance->setTable('properties');
        $query = $instance->newQuery();

        return (new BelongsTo($query, $this, 'property_id', $instance->getKeyName(), 'property'))
                    ->join('users', 'users.id', '=', 'properties.user_id')
                    ->select(DB::raw('users.*')
            );
    }
}

希望这对某人有帮助。

相关问题