【问题标题】:How to scope an Eloquent relation (or perform traditional join)如何定义 Eloquent 关系(或执行传统连接)
【发布时间】:2016-02-25 13:50:27
【问题描述】:

我正在尝试构建一组 Eloquent 模型,它们代表现有的硬件设备数据库(两者都不能更改)。我知道如何在 SQL 中执行此操作,但我正在努力构建使用第三个表的模型关系之一,类似于关系/联结表,但用于与复合键的一对一关系。

共有三个实体(简体):

  1. 设备
  2. 会话
  3. device_user

用户可以同时使用多个设备,并且拥有与这些设备相关联的会话日志。用户确实有一个唯一的 ID,但从设备的角度来看,他们只有一个“用户号”,它很短(3 个字节),因此不能代表整个用户范围,因此它被映射到 device_user 表中。 (实际上比这更复杂,但出于这个问题的目的,我已经将其剥离)

设备表:

d_id                PK
[data fields...]

device_user 表:

du_uid              User's actual ID
du_device_id        FK to device.d_id
du_number           000-999
[metadata...]

会话表:

s_device_id         device.d_id
s_user_number       000-999 (device_user.du_number)
[data fields...]

场景:我有一个会话,我想查找特定的 device_user.d_uid。在 SQL 中,我会执行以下操作:

SELECT session.blah, du_uid
FROM session
INNER JOIN device_user ON du_device_id = s_device_id AND du_number = s_user_number

所以我想这使它实际上只是一个复合键上的关系。

我在 Eloquent 中的尝试是这样的:

class SessionLogModel {

    public function device(){
        return $this->belongsTo('MyModels\\DeviceModel', 's_device_id', 'd_id');
    }

    public function user(){
        return $this->belongsTo('MyModels\\DeviceUserModel', 's_user_number', 'du_number')

        // A) I tried:
        ->withDevice($this->s_device_id);

        // or B) I tried:
        ->withDevice($this->device());

    }

    // example usage
    public static function getRecentUser(DateTime $localTime, $deviceId){
        $u = null;

        // get the preceding session log
        $q = SessionLogModel::where('session_type', '=', 'S')
            ->where('session_device_id', '=', $deviceId)
            ->where('sesison_date', '<=', $localTime)
            ->orderBy('session_id', 'DESC')
            ->take(1)
            ->with('device')
            ->with('user');
        $s = $q->get()->first();

        $u = $s->user->du_uid; // use the unique user ID
        ...
    }
}

class DeviceUserModel {
    // A)
    public function scopeWithDevice($query, $device_id){
        return $query->where('du_device_id', '=', $device_id);
    }
    // OR B) I tried:
    public function scopeWithDevice($query, $device){
        return $query->where('du_device_id', '=', $device->d_id);
    }
}

我尝试了多种方法来将匹配限制为具有范围或其他“where”构造的两列,但似乎总是无法通过 BelongsTo “发送”正确的值。检查 DB::getQueryLog 时,设备 ID 为 NULL。但是,如果我硬编码属性中的值,我可以看到它“工作”。

我对此进行了很多研究,但我发现很难找到一个类似的结构说明。

我正在使用来自 Laravel v4.2 的 Eloquent,独立使用(不在 Laravel 中)。

上述基于范围的方法是否可行? 还是我应该寻找不同的方法?

【问题讨论】:

  • 我建议使用 join 方法构建连接查询:laravel.com/docs/4.2/queries#joins
  • 我会试试hasManyThrough?或Eager Load Constraints -&gt;with('device', function ($query) {})。在声明关系的函数中使用模型属性是不可能的,因为在执行函数时模型尚未填充(这就是硬编码值有效但 $this-&gt;anything 无效的原因)

标签: php eloquent relational-database


【解决方案1】:

我刚刚遇到了这个有趣的问题: 我厌倦了在laravel中模拟你的表格如下:

public function up(){
    Schema::create('session', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('s_device_id');
        $table->string('s_user_number',20);
        $table->timestamps();
    });
    Schema::create('device', function (Blueprint $table) {
        $table->increments('d_id');
        $table->string('blah',20);
        $table->timestamps();
    });
    Schema::create('device_user', function (Blueprint $table) {
        $table->integer('du_device_id')->unsigned();
        $table->integer('du_uid')->unsigned();
        $table->string('du_number',20);
        $table->primary(['du_device_id', 'du_uid']);//important composite key
        $table->timestamps();
    });
}
//then do the relations on Medels:
//User Model
public function deviceUser(){
    return $this->hasOne(DeviceUser::class,'du_uid');
}
//Device Model
public function deviceUser(){
    return $this->hasOne(DeviceUser::class,'du_device_id','d_id');
}
//DeviceUser Model
public function device(){
    return $this->belongsTo(Device::class,'du_device_id','d_id');
}

public function user(){
    return $this->belongsTo(User::class,'du_uid');
}
//Session Model //[Not the Session Facade of Laravel]
public function device(){
    return $this->belongsTo(Device::class,'s_device_id');
}
//Now let us do the work in SessionController after filling your tables with demo data for e.g.
//all these relations are working fine!
    $device = Device::where('d_id',1)->first();
    $user = User::where('id',4)->first();

    //dd($user,$user->deviceUser,$device,$device->deviceUser);//here instance objects and their relations can be fetched easily

    $device_user = DeviceUser::where('du_device_id',1)->where('du_uid',4)->first();

    //dd($device_user,$device_user->device);
    //$session = Session::where('id',100)->first();//can get session by ID
    $session = Session::where('s_device_id',1)->where('s_user_number','000-999')->first();//get session by unique composite key which what you are after. It is similar to the sql Query that you built. Then you can easily fetch the relations as follows:
    dd($session,$session->device,$session->device->deviceUser);

希望这会有所帮助!

【讨论】:

  • 嗨 Scipilot,我知道这是一个迟到的答案,但请尝试检查我的答案,看看它是否对你有用。它基于雄辩的理性。问候。
猜你喜欢
  • 2021-01-05
  • 1970-01-01
  • 2018-08-20
  • 2018-01-21
  • 1970-01-01
  • 2013-10-20
  • 2014-05-08
  • 1970-01-01
  • 2013-12-08
相关资源
最近更新 更多