简体   繁体   中英

Can Laravel using join table to get data?

Just some random thought, can laravel using join table rather than using eloquent relationship. Because most of answers that i read in here suggest to using relationship like belongstoMany, belongsto and other eloquent relationship. If can, it should be nice if u guys giving me some sample code about how to do that. Sorry for the silly question. Thank you

A basic example using something I created a while ago using joins which were a forum thread table and a forum replies table. See below:

$forum = Forum::where('forumType', '=', $topic->forumType)
    ->leftJoin('forum_replies','forum_topics.forumid','=','forum_replies.topic_id')
    ->groupBy('forum_topics.forumid')
    ->orderBy('forum_replies.updated_at', 'DESC')
    ->get();

The above examples joins the forumid from forum_topics table to the forum_replies table's topic_id

Not a very tidy way of doing it though, you should definitely approach this by using relationships instead.

The code above was converted some time ago to relationships instead of using joins.

yes you can use the join as per your requirement if you don't want to add relationship like this

user::select('in_user_id', 'st_first_name', 'st_last_name', 
'in_contact_no', 'email', 'tbl_city.st_city_name', 
'tbl_usertype_master.st_usertype_name', 'tbl_center.st_center_name', 
'is_active')->leftjoin('tbl_city', 'tbl_city.in_city_id', 
'tbl_user.in_city_id')-> 
leftjoin('tbl_usertype_master','tbl_usertype_master.in_usertype_id', 
'tbl_user.in_usertype_id')->leftjoin('tbl_center', 
'tbl_center.in_center_id', 'tbl_user.in_center_id');

in this manner you can use join in laravel here i use for display user from User table

Hope this helps you

Thank You

Laravel查询构建器几乎支持所有SQL语句,您可以在此处查看所有可用的方法https://laravel.com/docs/5.5/queries

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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