当前位置:网站首页>Laravel 的关联模型 及其 预加载多个关联 with使用方法
Laravel 的关联模型 及其 预加载多个关联 with使用方法
2022-08-02 03:26:00 【陌潇】
预加载 关联模型 和 TP 一样 都是用with model 关联定义 大同小异
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Book extends Model
{
/**
* 获取书籍作者。
*/
public function author()
{
return $this->belongsTo('App\Author');
}
}
//控制器
$books = App\Book::with('author')->get();
foreach ($books as $book) {
echo $book->author->name;
}
预加载多个关联 有时,你可能需要在单一操作中预加载几个不同的关联。要达成此目的,只要向 with 方法传递多个关联名称构成的数组参数:
$books = App\Book::with(['author', 'publisher'])->get();
嵌套预加载 可以使用 「点」 语法预加载嵌套关联。比如在一个 Eloquent 语句中预加载所有书籍作者及其联系方式:
$books = App\Book::with('author.contacts')->get();
预加载指定列 并不是总需要获取关系的每一列。在这种情况下,Eloquent 允许你为关联指定想要获取的列:
$users = App\Book::with('author:id,name')->get();
注意:在使用这个特性时,一定要在要获取的列的列表中包含 id 列。
以上来自官方文档
但是有时候需要使用 「点」 语法预加载,但是又不需要那么多字段的话,比如在一个 Eloquent 语句中预加载所有书籍作者及其联系方式: 只需要查询作者的名字和联系方式的手机:
$books = App\Book::with(['author:id,name,contacts_id','author.contacts:id,phone'])->get();
边栏推荐
- hackmyvm-random walkthrough
- hackmyvm-bunny预排
- Kali环境下Frida编写脚本智能提示
- 考(重点理解哪些属于其他货币资金)、其他货币资金的内容、其他货币资金的账务处理(银行汇票存款、银行本票存款、信用卡存款、信用证保证金存款、存出投资款、外埠存款)
- 云安全笔记:云原生全链路加密
- After Alibaba Cloud sets up domain name resolution redirection, I cannot use Chrome to access it
- 一次代码审计的笔记(CVE-2018-12613 phpmyadmin文件包含漏洞)
- 2021-09-04 最简单的Golang定时器应用以及最简单的协程入门儿
- (6) Design of student information management system
- CSRF (Cross Site Request Forgery)
猜你喜欢
清理c盘爆满告急,C盘清理
文件上传漏洞
The shooting range that web penetration must play - DVWA shooting range 1 (centos8.2+phpstudy installation environment)
(1) print()函数、转义字符、二进制与字符编码 、变量、数据类型、input()函数、运算符
File upload vulnerability
hackmyvm-random walkthrough
hackmyvm: juggling walkthrough
(5) Modules and packages, encoding formats, file operations, directory operations
file contains vulnerabilities
会计凭证概述、原始凭证、原始凭证的种类、原始凭证的基本内容、原始凭证的填制要求、原始凭证的审核
随机推荐
Mysql创建索引
PHP实现搜索框的自动反查提示
The first time to tear the code by hand, how to solve the problem of full arrangement
元宇宙:为何互联网大佬纷纷涉足?元宇宙跟NFT是什么关系?
CTF入门之md5
Shuriken: 1 vulnhub walkthrough
会计凭证概述、原始凭证、原始凭证的种类、原始凭证的基本内容、原始凭证的填制要求、原始凭证的审核
What are the killer super powerful frameworks or libraries or applications for PHP?
The shooting range that web penetration must play - DVWA shooting range 1 (centos8.2+phpstudy installation environment)
CTF入门笔记之SQL注入
元宇宙是一个炒作的科幻概念,还是互联网发展的下半场?
PALISADE:CKKS的使用
Command Execution Vulnerability
hackmyvm: may walkthrough
Phonebook
uniapp | Compilation error after updating with npm update
Smart Tips for Frida Scripting in Kali Environment
Phonebook
The CTF introduction of PHP file contains
17. JS conditional statements and loops, and data type conversion