Laravel 连接表 [英] Laravel join tables

查看:21
本文介绍了Laravel 连接表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 张桌子,我需要加入这些桌子.我需要从 galleriesselect idname,其中共享 gal.id = 画廊.iduser_id = auth::id().

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

表格:

Galleries: id, name
Share: gal_id, user_id

请给我看 Laravel 中的例子.我需要显示它.

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

推荐答案

为了实现这一点,您需要在 Eloquent ORM 中建立关系.官网声明:

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

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

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:

你可以在这里

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

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();

上面的查询会根据 user.id = profile.id 两个不同的条件连接两个表,分别是usersprofiles,你可以使用也可以不使用where 子句,这完全取决于您要实现的目标.

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

这篇关于Laravel 连接表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆