Laravel5 Eloquent ORM 查询

xiaoxiao2021-02-28  26

Subject.php

<?php namespace App\Models; /** * 题目表 * * Class Subject * @package App\Models */ class Subject extends BaseModel { /** * 数据表 * */ protected $table = 'subjects'; /** * 主键 * */ protected $primaryKey = 'subject_id'; /** * 关联科目类型 * * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function subjectClass() { return $this->belongsTo('App\Models\SubjectClass', 'class_id', 'class_id'); } }

TestController.php

public function testOne() { // 特别注意 class_id,class_id 是关联字段 $data = Subject::where('subject_id', 1)->with(['subjectClass' => function($query) { $query->select('class_id','class_name'); }])->select('class_id','subject_id')->first(); } public function testTwo() { $args = ['class_id','class_name']; $mainArgs = ['class_id', 'subject_id', 'created_at']; $data = Subject::where('subject_id', 1)->with(['subjectClass' => function($query) use ($args, $mainArgs) { $query->select($args); }])->select($mainArgs)->first(); } public function testThree() { $data = Subject::where('subject_id', 1)->with('subjectClass')->first(); } public function testFour($created_at) { // whereHas 和 orWhereHas 允许添加自定义条件约束到关联关系条件约束,只显示 subjects 表数据 $data = Subject::where('subject_id', 1)->whereHas('subjectClass', function ($query) use ($created_at) { $query->where('created_at', $created_at); })->first(); } public function testFive() { // 输出 SubjectClass 对象信息 $data = Subject::find(1)->subjectClass()->first(); dd($data); } public function testSix() { // 输出 SubjectClass 对象信息 $data = Subject::find(1)->subjectClass; dd($data); }

PS:with 方法可以进行简化,在 Model 基类中定义一个范围查询

use Illuminate\Database\Eloquent\Model; class BaseModel extends Model{ // 注意 scopeWithOnly public function scopeWithOnly($query, $relation, Array $columns) { return $query->with([$relation => function ($query) use ($columns){ // 这里根据具体业务进行调整,有些表可能不含有 id 字段 $query->select(array_merge(['class_id'], $columns)); }]); } } $data = Subject::where('id', '>', '10')->withOnly('subjectClass', ['class_name'])->get();
转载请注明原文地址: https://www.6miu.com/read-2150273.html

最新回复(0)