【发布时间】: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->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 子句后附加
->first()或->get(),例如Test::where(1)->first()