Home > Backend Development > PHP Tutorial > 一个比较复杂的laravel orm eloquent查询

一个比较复杂的laravel orm eloquent查询

WBOY
Release: 2016-06-06 20:24:03
Original
1557 people have browsed it

表结构如下:

<code>表名:projects
字段:id, name

表名:projects_services(1 project_id  M service_id)
字段:project_id, service_id

表名:services
字段:id, name

表名:services_modules(M service_id  N module_id)
字段:service_id, module_id

表名:modules
字段:id, name

表名:modules_scripts(1 module_id1 script_id)
字段:module_id, script_id

表名:scripts
字段:id, name</code>
Copy after login
Copy after login

如果我想利用laravel的eloquent查询如下信息,应该如何实现呢?

script_id, script_name, module_name, service_name, project_name

回复内容:

表结构如下:

<code>表名:projects
字段:id, name

表名:projects_services(1 project_id  M service_id)
字段:project_id, service_id

表名:services
字段:id, name

表名:services_modules(M service_id  N module_id)
字段:service_id, module_id

表名:modules
字段:id, name

表名:modules_scripts(1 module_id1 script_id)
字段:module_id, script_id

表名:scripts
字段:id, name</code>
Copy after login
Copy after login

如果我想利用laravel的eloquent查询如下信息,应该如何实现呢?

script_id, script_name, module_name, service_name, project_name

可以实现的,而且laravel会实现的非常优雅, 你这里是
projects->project_services->services->services_modules->modules->modules_scripts->scriputs,七表联合查询,你首先要把这七个模型创建好,并且要定义好各自得关联关系,然后:$list =Projects::with('project_services.services.services_modules.modules.modules_scripts.scripts')->where('写上你的条件')-first(); 只需要这么简短的一句代码,就可以实现你的需求,就能非常方便的获取你所要的数据 project_name:$list->name, service_name:$list->project_services->services->name; module_name:$list->project_services->services->services_modules->modules->name; sript_name:$list->project_services->services->services_modules->modules->modules_scripts->scripts->name; sript_id:$list->project_services->services->services_modules->modules->modules_scripts->scripts->id; 这种方法我用的较多,非常的方便,但是像这么长的连接查询,我还没有用过。

一楼已经说的不错

先在laravel eloquent定义这几个表的关系,文档地址:http://laravel.com/docs/5.1/eloquent-relationships

然后可以直接在controller中,使用Projects::with(...你需要的内容)就可以了。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template