【发布时间】:2018-03-25 18:18:37
【问题描述】:
我正在尝试在 MySQL 查询中加入数据透视表。基本上我是在选择用户,其中一个用户有多个子类别。
所以本质上,对于我的“sub_categories”关系,一个用户有许多子类别。但因为我使用的是 RAW 选择,所以我无法选择/使用关系。相反,我必须使用联接。
这是我的 sub_categories 表
列类型注释 id int(10) 无符号自动增量 main_category_id int(10) 无符号 [0] 类别名称 varchar(100) created_at 时间戳 NULL updated_at 时间戳 NULL这是我的数据透视表
列类型注释 user_id int(10) 无符号 sub_category_id int(10) 无符号这是我的 SQL 查询
$users= DB::table('users') ->select('users.*', 'user_options.*', DB::raw(' 分支。*, Professional_profiles.tags, ' . $拉特。 ' 作为 latpoint, ' .美元 . ' 作为长点, ' . $半径。 ' 作为半径, ' . $measurement_number 。 ' 作为距离单位, ( ' . $measurement_number 。 ' * 度数( ACOS( COS(弧度(' . $lat . ')) * COS(弧度(branches.lat)) * COS(RADIANS(' . $lng . ' - 分支.lng)) + 罪(弧度(' . $lat . ')) * 罪(弧度(branches.lat)) ) ) ) 作为距离 '), 'users.id AS id') ->leftJoin('branches', 'users.branch_id', '=', 'branches.id') ->leftJoin('user_options', 'user_options.user_id', '=', 'users.id') ->leftJoin('professional_profiles', 'professional_profiles.user_id', '=', 'users.id') ->where('user_options.professional', '>', 0) ->where('users.branch_id', '>', 0) ->where(函数 ($x) 使用 ($term) { $x->where('branches.branch_name', 'like', '%' . $term . '%') ->orWhere('branches.branch_city', 'like', '%' . $term . '%') ->orWhere('users.firstname', 'like', '%' . $term . '%') ->orWhere('users.lastname', 'like', '%' . $term . '%') ->orWhere('professional_profiles.tags', 'like', '%' . $term . '%'); }) ->有('距离','orderBy('距离','asc') ->限制(50) ->获取();这是我的结果:
[ { 编号:4, profile_id: 2, 分支ID:3, 前缀:“博士”, 名字:“SWK1”, 姓氏:“Doe”, 电子邮件:“swk1@gmail.com”, mobile_no: "811692244", 密码:"$2y$10$LzkPwc2TZu/.UzB.0mYJ", 头像: "123.jpg", remember_token: "wF33ShLirtvS3mIYJpmg5skVVoohGJCS7v", created_at: "2017-10-12 09:32:05", 更新时间:“2017-10-12 09:32:05”, 提供者:空, provider_id:空, 用户 ID:4, profile_administrator: 0, 分支管理员:0, 专业:1、 branch_name: "斯瓦科普蒙德 1", branch_address_1: "14 Backer St", 分支地址_2:空, branch_city: "斯瓦科普蒙德", 分支状态:空, branch_zip: "9000", 分支国家:“NA”, 分支电话:“77777”, 主图像:空, 纬度:-22.67, 液化天然气:14.53, 描述:“斯瓦科普蒙德 1”, 标签: "医生,营养师,全科医生", 纬度:“-22.5608807”, 长点:“17.0657549”, 半径:500, 距离单位:“111.045”, 距离:260.210154298872 } ]所以本质上,问题是通过使用数据透视表设置的值,将 sub_categories 表连接到 users 表上,而不依赖 eloquent 关系表,而是使用 SQL。
由于一个用户有许多 sub_categories,最好将 sub_categories 作为连接到主 SQL 查询的数组值返回。
【问题讨论】:
-
我有完全相同的情况,我使用范围和 with() 方法来获取与用户关联的子类别数组。我会找到我的代码并发布同时你可以看stackoverflow.com/questions/26178315/…
标签: php mysql laravel join pivot