繁体   English   中英

将2个表连接在一起,并返回匹配的所有数据(使用MySQL的PHP​​ / Laravel5.2)

[英]Join 2 tables together and get return all data where it matches (PHP/Laravel5.2 using MySQL)

我有一个名为$ category的变量,用户可以选择。 在提交时,我需要查看$ category匹配的表(配置文件),然后拉回所有这些配置文件,然后查看Likes表并返回返回的配置文件的所有匹配记录。

我的数据库如下所示:

表:个人资料

ID |   username  | category
-------------------------
 1 |      x      | band  
 2 |      y      | airline
 3 |      z      | airline

表:喜欢

ID | account_id  | likes  | created_at
---------------------------------------
 1 |      2      | 1000   | 21/03/2016
 2 |      2      | 2000   | 22/03/2016
 3 |      1      | 3000   | 22/03/2016

我的代码如下:

$category = "band";

$profiles = DB::table('profiles')
            ->join('likes', 'profiles.id', '=', 'likes.account_id')
            ->where('category', '=', $category)
            ->select('profiles.*', 'likes.likes', 'likes.created_at')
            ->get();

likes表中的account_id与profiles表中的id相同。 每个配置文件也可能有多个相似的记录。 该查询似乎不起作用,并且没有返回任何内容。 我正在使用laravel 5.2。

 $profiles = DB::table('profiles')
        ->leftJoin('likes', 'profiles.id', '=', 'likes.account_id')
        ->where('profiles.category', '=', $category)
        ->select('profiles.*', 'likes.likes', 'likes.created_at')
        ->get();

暂无
暂无

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

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