这是PHP Laravel,SQL LeftJoin查询问题。 我有2个表分别命名为“ stories”和“ favorite_story”。我想返回“故事”表中的所有值,并基于“ story_id”返回“ favorite_story”表中的匹配值,这是两个表中的通用字段。
以数组形式显示的结果可以看到“ story_id”,“ user_id”的结果为空,不应为空。 Fav_id为空,可以,因为“ favorite_story”表为空。
我希望从“故事”表中获取“ story_id”,并希望从“ favorite_story”表中获取“ user_id”。
这是我的控制器代码:
public function fanfiction(){
$user_id = Session('userid');
$data['stories'] = DB::table('stories')
->leftJoin('favorite_story', 'favorite_story.story_id','=','stories.story_id')
->Select('*')
->get();
return view('fanfiction', $data);
}
这是上面代码以数组形式的结果。
[0] => stdClass Object
(
[story_id] =>
[story_title] => Third Story
[story_desc] => This is "Times" story summary.
[img] => 2018-12-26-70pgFK87ZN.png
[story_genre] => Fighting
[story_character] => Aoba Y.
[story_rating] => Adult Only
[story_warning] => Drug Use
[story_date] => December 26, 2018
[series_id] => 9999999
[user_id] =>
[fav_id] =>
)
[1] => stdClass Object
(
[story_id] =>
[story_title] => Second Story
[story_desc] => This is summary of this new story.
[img] => 2018-12-19-e6JnEpo3ky.jpg
[story_genre] => Friendship
[story_character] => Aijsai
[story_rating] => G
[story_warning] => Rape (Actual)
[story_date] => December 19, 2018
[series_id] => 9999999
[user_id] =>
[fav_id] =>
)
任何帮助将不胜感激。
答案 0 :(得分:0)
将查询更改为:
public function fanfiction()
{
$user_id = session->get('userid');
$data['stories'] = DB::table('stories')
->leftJoin('favorite_story', 'favorite_story.story_id','=','stories.story_id')
->select('stories.*') // add other fields that you need from favorite_story table here
->get();
return view('fanfiction', $data);
}
发生这种情况的原因是,它是从user_id
表中获取story_id
和favorite_story
,在这种情况下为空。