首页 > 解决方案 > Eloquent 模型作为建造者回归

问题描述

我正在使用 laravel 7 重新学习 Laravel,并且遇到了一个问题,即我无法在我的数据库表中查询记录。因此,不是像这样的调用$test = Test::find_by_id_and_name(1, 'test 1');(并且还$test = Test::where('id', 1);返回一个类 Illuninate\Database\Eloquent\Model,而是返回一个类 Illuminate\Database\Eloquent\Builder。

我为一个名为 Tests 的表创建了一个 Migration,并为其添加了几行测试数据。App中的测试模型如下

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Test extends Model
{
    protected $guarded = [];
    use SoftDeletes;

}

迁移是:

se Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateTestsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tests', function (Blueprint $table) {
            $table->id();
            $table->string( 'name' );
            $table->string( 'url', 255 );
            $table->timestamps();
            $table->softDeletes();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('tests');
    }
}

所以任何人都知道为什么我没有得到我需要的模型,所以我可以做例如 add($test);并查看存储在数据库中 id 为 1 的行的值?甚至做一个echo($test->name);看看这个项目的名称?

谢谢

* 附加 * 应该指出我的初始代码有 Test::find_by_id_and_name(1, 'test 1'); 但这不起作用,并引发了有关查找课程的异常。我修改了 if with where and above 是一个错字,因为它是 where('id', 1 ); (我已经使用我最初的 find_by 代码更正了代码)。添加 get() 或任何其他内容现在返回 null。我已验证数据库包含表测试,并且存在 id 和名称为“test 1”的项目

* 结果 * 最后的根本问题是数据,网址中有 https::// (附加冒号),所以它确实会返回 null。谢谢大佬帮我找原因。

标签: phplaraveleloquent

解决方案


对 . 中查询生成器与模型的Laravel误解 检查文档以供参考。

在模型上静态调用查询构建器方法会返回一个构建器。

User::where('id', 1); // returns builder

要解析查询生成器,您可以使用get()first()

User::where('id', 1)->get(); // Returns a collection of users with 1 element.
User::where('id', 1)->first(); // Returns one user.

您还可以从不推荐的集合中获取用户,因为您不妨调用first().

User::where('id', 1)->get()->first(); // Returns collection fetches first element that is an user.

Laravel具有通过 id 查找模型的静态方法。

User::find(1); // returns user or null
User::findOrFail(1); // returns user or exception

推荐阅读