当前位置:网站首页>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();边栏推荐
- Basic use of v-on, parameter passing, modifiers
- The learning path of a network security mouse - the basic use of nmap
- WeChat applet development video loading: [Rendering layer network layer error] Failed to load media
- 一次代码审计的笔记(CVE-2018-12613 phpmyadmin文件包含漏洞)
- hackmyvm-hopper预排
- (3) string
- 加密数字货币前传:从大卫·乔姆到中本聪
- Introduction to PHP (self-study notes)
- 借贷记账法下的账户结构、借贷记账法的记账规则、借贷记账法下的账户对应关系与会计分录
- 解决flex布局warp自动换行下最后一行居中问题
猜你喜欢

管理会计(对内)指引、管理会计要素及其具体内容(可能考,考前记一下,推荐记一下四个大点即可)、

The shooting range that web penetration must play - DVWA shooting range 1 (centos8.2+phpstudy installation environment)

hackmyvm: again walkthrough

Activity

hackmyvm: juggling walkthrough

The CTF introduction of PHP file contains

(7) superficial "crawlers" process (concept + practice)

Praying: 1 vulnhub walkthrough

hackmyvm: may walkthrough

hackmyvm: may walkthrough
随机推荐
How to log in to Alibaba Cloud server using the admin account
ES6 iterator explanation example
CTF入门笔记之SQL注入
考(重点理解哪些属于其他货币资金)、其他货币资金的内容、其他货币资金的账务处理(银行汇票存款、银行本票存款、信用卡存款、信用证保证金存款、存出投资款、外埠存款)
centos8 安装搭建php环境
[Hello World教程] 使用HBuilder和Uni-app 生成一个简单的微信小程序DEMO
什么是广告电商商业模式?这几个门派告诉你
GreenOptic: 1 vulnhub walkthrough
c语言用栈实现计算中缀表达式
(4) 函数、Bug、类与对象、封装、继承、多态、拷贝
【无标题】
战场:3(双子叶植物)vulnhub走读
命令执行漏洞
重点考:从债劵的角度来看交易性金融资产
web安全之目录遍历
mysql 原生语句点滴学习记录
PALISADE:CKKS的使用
hackmyvm: again walkthrough
一个网络安全小白鼠的学习之路——nmap的基本使用
Summary of php function vulnerabilities