当前位置:网站首页>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: controller walkthrough

Google Hacking

元宇宙:为何互联网大佬纷纷涉足?元宇宙跟NFT是什么关系?

VIKINGS: 1 vulnhub walkthrough

Eric靶机渗透测试通关全教程

How to calculate the distance between two points on the earth (with formula derivation)

【泰山众筹】模式为什么一直都这么火热?是有原因的

hackmyvm: again walkthrough

会计账簿、会计账簿概述、会计账簿的启用与登记要求、会计账簿的格式和登记方法

链动2+1无限循环系统,2022年起盘成功率超高的模式
随机推荐
重点考:从债劵的角度来看交易性金融资产
Offensive and defensive world - novice MISC area 1-12
hackmyvm: kitty walkthrough
Basic use of v-on, parameter passing, modifiers
(2) 顺序结构、对象的布尔值、选择结构、循环结构、列表、字典、元组、集合
(1) introduction to Thinkphp6, installation view, template rendering, variable assignment
英语每日打卡
【无标题】
(1) the print () function, escape character, binary and character encoding, variables, data type, the input () function, operator
file contains vulnerabilities
Command Execution Vulnerability
How to determine the direction based on two coordinate points on the map
uniapp | Problems with the use of the official map component
hackmyvm-bunny walkthrough
同态加密:CKKS原理之旋转(Rotation)
By figure, a (complete code at the end)
最简单的FRP内网穿透教程
hackmyvm-random walkthrough
PHP realizes the automatic reverse search prompt of the search box
Alfa: 1 vulnhub walkthrough