php Laravel 连接表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27459380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:23:04  来源:igfitidea点击:

Laravel join tables

phplaraveljoin

提问by Jensej

I have 2 tables and I need to join those tables. I need to selectidand name from galleries, where share gal.id = galleries.idand user_id = auth::id().

我有 2 张桌子,我需要加入这些桌子。我需要selectidname from galleries,在那里共享gal.id = galleries.iduser_id = auth::id().

Tables:

表格:

Galleries: id, name
Share: gal_id, user_id

Please show me example in laravel. And I need to display it.

请给我看laravel中的例子。我需要展示它。

回答by Khan Shahrukh

To achieve this, you have Relationship in Eloquent ORM. The official website states :

为了实现这一点,您需要在 Eloquent ORM 中建立关系。官方网站指出:

Of course, your database tables are probably related to one another. For example, a blog post may have many comments, or an order could be related to the user who placed it. Eloquent makes managing and working with these relationships easy. Laravel supports many types of relationships:

当然,您的数据库表可能彼此相关。例如,一篇博文可能有很多评论,或者一个订单可能与放置它的用户相关。Eloquent 使管理和处理这些关系变得容易。Laravel 支持多种类型的关系:

You can read all about eloquent relationship over here

您可以在此处阅读有关雄辩关系的所有信息

If you do not want to use relationship, following is an example on how to join two tables :

如果您不想使用关系,以下是有关如何连接两个表的示例:

   DB::table('users')
->select('users.id','users.name','profiles.photo')
->join('profiles','profiles.id','=','users.id')
->where(['something' => 'something', 'otherThing' => 'otherThing'])
->get();

The above query will join two tables namely usersand profileson the basis of user.id = profile.id with two different conditions, you may or may not use whereclause, that totally depends on what you are trying to achieve.

上面的查询将加入两个表,即usersprofilesuser.id = profile.id具有两种不同条件的基础上,你可能会或可能不会使用where条款,即完全取决于你想要达到的目的。