【发布时间】:2021-10-29 01:32:14
【问题描述】:
我一直在尝试用谷歌搜索,但我仍然无法确定我脑海中问题的确切答案。
我使用php artisan 创建了一个迁移文件来设置一个名为blogs 的表(注意复数形式)。以前,该表称为blog(单数),工厂不会播种,因为终端上显示的错误是no relations found for "blogs"——这对我来说没有意义,因为我在控制器、模型和工厂是单一的。在我回滚迁移并以复数形式将表重新创建为 blogs 之前,它不会让我播种。
最奇怪的是,我仍然将其他所有内容都保留为单数,有人知道为什么播种只有在我使用复数作为表名时才有效吗?
这是我将表格从blog修改为blogs后的迁移文件:
class CreateBlogsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('blogs', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->string('title', 255);
$table->text('body');
$table->text('user_id');
});
}
这是我的工厂 - 名为BlogFactory:
namespace Database\Factories;
use App\Models\Blog;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
class BlogFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = Blog::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'title' => $this->faker->sentence, //Generates a fake sentence
'body' => $this->faker->paragraph(30), //generates fake 30 paragraphs
'user_id' => User::factory() //Generates a User from factory and extracts id
];
}
}
这是我的模型 - 名为Blog:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Blog extends Model
{
use HasFactory;
protected $fillable = [
'title',
'body',
'user_id',
];
}
这是我的控制器 - 名为 BlogController:
<?php
namespace App\Http\Controllers;
use App\Models\Blog;
use Illuminate\Http\Request;
class BlogController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return Blog::all();
}
【问题讨论】:
-
没有代码很难帮助你——你把
protected $table = 'blog';放在模型里了吗? Laravel 默认将模型的表名复数化,因为你决定更改需要通知 Laravel 你这样做了。如果不是,您很可能在播种机中打错了字。此外,该错误表示找不到博客的关系。您是否打算与用户建立博客关系?这里可能有很多事情是错误的。最好的建议是坚持使用 Laravel 的默认设置,直到您获得更多经验。很难同时对抗框架和学习 -
嗨@NicklasKevinFrank,我添加了代码供参考。这些代码是我对“博客”所做的唯一参考。我只调用了路由
api.php中的数据,这些数据返回到控制器 - 例如Route::get('/blogs', [BlogController::class, 'index']); -
等等...您要更改已在运行的应用程序的迁移吗?
-
我没改过。我刚开始这个项目,我正在设置迁移。我的意图是将博客表命名为单数,然后继续播种。但是当我播种时,终端只会尖叫“找不到博客的关系”。所以我解决这个问题的唯一方法是使用复数形式的“博客”。仅供参考 - 我还没有“php artisan serve”。我只是在播种。
-
这能回答你的问题吗? Laravel seed issue, laravel is looking for plural table name。在做任何事情之前阅读documentation 有多难?您是否试图通过不阅读并猜测所有内容来学习框架?也有人问过这个问题......阅读文档和搜索东西有多难......我厌倦了这个问题......
标签: laravel postgresql seed