【问题标题】:Eloquent model is returning as builderEloquent 模型作为建造者回归
【发布时间】:2020-06-22 19:10:44
【问题描述】:

我正在使用 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 的表创建了一个迁移,并为其添加了几行测试数据。 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');
    }
}

所以任何人都知道为什么我没有得到我需要的模型,所以我可以做一个dd($test); 并查看存储在数据库中 id 为 1 的行的值?或者甚至做一个echo($test-&gt;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。谢谢大家帮我找到原因。

【问题讨论】:

  • 在 where 子句后附加 -&gt;first()-&gt;get(),例如 Test::where(1)-&gt;first()

标签: php laravel eloquent


【解决方案1】:

Laravel 中的查询生成器与模型的误解。参考doc

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

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

【讨论】:

  • 这里的链接在这个答案中也很好:laravel.com/docs/7.x/eloquent
  • 我已经根据你们的 rthe cmets 更新了我的问题。尽管存在表和数据行,但我现在为空。
  • 很高兴您将 "[...] not推荐" 用于-&gt;get()-&gt;first()。值得注意的是,Collection-&gt;get() 的结果)有一个 -&gt;first() 方法,但在少数情况下您需要使用该方法。
  • @TimLewis 我也只是觉得很高兴知道你可以,了解什么是集合,当我第一次开始学习如何做事时花了一些时间,这很难。
  • 哈哈是的,当然 :) 更多的知识总是好的,但是知道什么时候使用所说的知识的智慧也是如此:P
【解决方案2】:

尝试使用以下方法

$test = Test::find(1);

然后你就会得到记录,

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-10
    • 1970-01-01
    • 2016-11-22
    • 1970-01-01
    相关资源
    最近更新 更多