如何从 Eloquent 模型中检索记录?

How to retrieve record from Eloquent Model?

这听起来很愚蠢,但我找不到从 eloquent 模型 Gallery.php:

中检索记录的方法
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Gallery extends Model
{
    use HasFactory;

    protected $fillable = ['text'];
}

web.php 中的路线呼叫:

$data = Gallery::with('id', '=', 1)->get();

laravel.log 中抛出此错误:

local.ERROR: Call to undefined relationship [id] on model [App\Models\Gallery]. {"exception":"[object] (Illuminate\Database\Eloquent\RelationNotFoundException(code: 0): Call to undefined relationship [id] on model [App\Models\Gallery]. at /Users/artur/PhpstormProjects/strong-moebel.art/vendor/laravel/framework/src/Illuminate/Database/Eloquent/RelationNotFoundException.php:35)

唯一有效的是:

$data = Gallery::all();

with() 方法位于:

Gallery::with

用于表示与另一个模型的关系。 如果您只想从 Gallery 模型中获取数据,请将 with() 更改为 where(),如下所示:

$data = Gallery::where('id', '=', 1)->get();

这将 return 一个集合(将其视为包含结果数组的对象)。

如果您尝试从相关模型访问其他数据,则需要根据 Laravel 文档设置关系。

如果您只想要与该 ID 相关的 Gallery 实例,您可以使用

获取它
$gallery = Gallery::where('id', '=', 1)->first();
// or
$gallery = Gallery::find(1);