简体   繁体   English

仅从联接表中获取选定的列

[英]get only the selected column from the join table

I have this reference code below, first the line 1 will get 我在下面有此参考代码,首先是第1行

$aa = users_details::select(array('id', 'user_id'))->where('id', '=', $request->id)->first(); //first line
$bb = User::select(array('user_id'))->where('user_id', '=', $aa->id)->with('user_details')->first(); //second line

the first line returns 13 which is correct while the second line returns 'null' which it should not because there's actually a record that has a user_id of '13'. 第一行返回正确的13,而第二行返回“ null”,这不应该,因为实际上有一条记录的user_id为“ 13”。 Any ideas, help please? 有什么想法,请帮忙吗?

and also is there a way I could select only selected columns in this join table (Eloquent relationship hasOne) 而且还有一种方法我可以只选择此联接表中的选定列(雄辩关系hasOne)

$bb = User::select(array('user_id'))->where('user_id', '=', $aa->id)->with('user_details')->first();

I dont know if 我不知道

select(array('user_id')) 选择(数组('user_id'))

is the right one to select only selected columns from the join table. 是从联接表中仅选择选定列的正确选择。 Any ideas, help, please? 有什么想法,请帮忙吗?

First Question: 第一个问题:

$bb = User::select(array('user_id'))->where('user_id', '=', $aa->id)->with('user_details')->first();

Do you have user_id column in users (or anywhere User Model refers to) table? 用户表(或User模型所指向的任何地方)中是否有user_id列? Do you have user_details method in User model? 您在用户模型中是否有user_details方法?

Second Question: 第二个问题:

You can select as 您可以选择

User::select('user_id', 'username', 'sex')

If you have same column name in the joined table, then you can select as 如果联接表中的列名相同,则可以选择

User::select('users.user_id as a', 'users.username', 'users.sex', 'user_details.user_id as b')

UPDATE: 更新:

How can I select only selected column from the 'user_details' when both is joining togehter? 当两者都一起加入时,如何从“ user_details”中仅选择选定的列?

User::select('users.user_id as user_id', 'users.username', 'users.sex', 'user_details.user_id as user_details_id')->join('user_details','user_details.user_id','=', 'users.id' )->where('users.id', '=', $aa->id)->first();

To select the columns from the joined table, just prefix the column name with table name such as user_details.user_id . 要从联接表中选择列,只需在列名前加上表名,例如user_details.user_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM