Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel 使用where和relations查找有说服力的模型_Laravel_Eloquent_Octobercms - Fatal编程技术网

Laravel 使用where和relations查找有说服力的模型

Laravel 使用where和relations查找有说服力的模型,laravel,eloquent,octobercms,Laravel,Eloquent,Octobercms,我有三个数据库表、集线器、房间和设备,如下所示 数据库表和列 集线器:id,name 房间:id、hub\U id、姓名 设备:id、房间id、名称 你可以想象,我有三个模型 class Hub extends Model { public $hasMany = ['rooms' => ['Models\Room']]; } class Room extends Model { public $hasMany = ['devices' => ['Models\Devic

我有三个数据库表、集线器、房间和设备,如下所示

数据库表和列

  • 集线器:id,name
  • 房间:id、hub\U id、姓名
  • 设备:id、房间id、名称
你可以想象,我有三个模型

class Hub extends Model {
  public $hasMany = ['rooms' => ['Models\Room']];
}

class Room extends Model {
  public $hasMany = ['devices' => ['Models\Device']];
  public $belongsTo = ['hub' => [
        'Models\Hub',
        'key' => 'hub_id'
  ]];
}

class Device extends Model {
  public $belongsTo = ['room' => [
        'Models\Room',
        'key' => 'room_id'
  ]];
}
我有以下数据记录

枢纽

  • 1号,HubOne
  • 2,2
房间和设备(例如)

  • 轮毂(1)客厅(客厅灯、走道灯)
  • 轮毂(1)卧室(卧室灯、台灯)
  • 轮毂(1)厨房(台灯)
  • 轮毂(2)客厅(客厅灯、走道灯)
我想按集线器id和特定术语查找设备。集线器id应完全匹配。术语应该是“LIKE”房间名称或设备名称

例如:hub_id=1,term=“客厅”

结果应为Hub(1)客厅中的所有设备

例如:hub_id=1,term=“台灯”

结果应该是卧室和厨房的两盏灯

但是如果hub_id=1,term=“客厅灯”

结果应该是唯一与名称匹配的灯光

如何使用雄辩的Models&Collections查询样式而不是原始查询来实现这一点?我下面的脚本非常接近,但仍然不正确。请帮忙

$rooms = Room::with('devices')
        ->where('hub_id', $hub_id)
        ->where(function ($query) use ($term) {
            $query->whereHas('devices', function ($query) use ($term) {
                $query->where('device_name', 'LIKE', '%' . $term . '%');
            })->orWhere('title', 'LIKE', '%' . $term . '%');
        })->get();

$devices = $rooms->lists('devices');
此代码应适用于:

$devices = Device::where(function($query) use ($term) {
    $query->where('device_name', 'like', '%' . $term . '%')
        ->whereIn('room_id', function($sub_query) use ($term) {
            $sub_query->select('id')->from('rooms')
                ->where('room_name', 'like', '%' . $term . '%');
        }, 'or')
    })
    ->whereIn('room_id', function ($query) use ($hub_id) {
            $query->select('id')->from('rooms')
            ->where('hub_id', $hub_id)
    })->get();