Cra*_*eld 6 php laravel 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 的表创建了一个迁移,并在其中添加了几行测试数据。App中的测试模型如下
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Test extends Model
{
protected $guarded = [];
use SoftDeletes;
}
Run Code Online (Sandbox Code Playgroud)
迁移是:
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');
}
}
Run Code Online (Sandbox Code Playgroud)
那么有人知道为什么我没有得到我需要的模型,以便我可以执行例如 add($test);并查看数据库中存储的 id 为 1 的行的值吗?或者甚至做一下echo($test->name);并查看该项目的名称?
谢谢
* 另外 * 应该指出我的初始代码有 Test::find_by_id_and_name(1, 'test 1'); 但这不起作用并抛出有关查找类的异常。我修改了 if 与 where 和上面是一个拼写错误,因为它是 where( 'id', 1 ); (我已经使用最初的 find_by 代码更正了代码)。添加 get() 或任何其他内容现在返回 null。我已验证数据库包含表测试,并且存在 id 和名称为“test 1”的项目
* 结果 * 最终的根本问题是数据,url 中包含 https::// (额外的冒号),所以实际上它会返回 null。谢谢各位帮我找到原因了。
对查询构建器与模型的误解Laravel。检查文档以供参考。
在模型上静态调用查询构建器方法会返回一个构建器。
User::where('id', 1); // returns builder
Run Code Online (Sandbox Code Playgroud)
要解析查询生成器,您可以使用get()或first()。
User::where('id', 1)->get(); // Returns a collection of users with 1 element.
User::where('id', 1)->first(); // Returns one user.
Run Code Online (Sandbox Code Playgroud)
您还可以从集合中获取用户,但不建议这样做,因为您最好直接调用first().
User::where('id', 1)->get()->first(); // Returns collection fetches first element that is an user.
Run Code Online (Sandbox Code Playgroud)
Laravel有通过 id 查找模型的静态方法。
User::find(1); // returns user or null
User::findOrFail(1); // returns user or exception
Run Code Online (Sandbox Code Playgroud)