如何用自定义外键行为修复这个Laravel一对多的问题?



我是laravel的新手,并试图用一个(客户)对许多(表)关系和一个自定义外键tables制作两个表。customer(I can not change this)

连接通过customersidtablescustomer.

运行php artisan migrate:fresh --seed后,一切都按预期创建。但是tablescustomer总是0。我没有得到任何错误。这两个表都正确创建了。我错过了什么?

以下是我的设置:模型:

Customers.php

namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
class Customers extends Model {
use HasFactory;
public function tables() {
return $this->hasMany(Tables::class, 'customer');
}
public $timestamps = false;
}

Tables.php

namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
class Tables extends Model {
use HasFactory;
public function customers() {
return $this->belongsTo(Customers::class, 'customer');
}
public $timestamps = false;
}

迁移:

客户

use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;
return new class extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up() {
Schema::create('customers', function (Blueprint $table) {
$table->string('id', 6)->primary();
$table
->string('img', 23)
->nullable()
->default(null);
$table->tinyText('name');
$table->tinyInteger('active')->default(1);
$table->bigInteger('created'); // unix timestamp when created
$table
->bigInteger('status')
->nullable()
->default(null); // null not deleted / unix timestamp when deleted
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down() {
Schema::dropIfExists('customers');
}
};

use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;
return new class extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up() {
Schema::create('tables', function (Blueprint $table) {
$table->string('id', 8)->primary();
$table->tinyText('number');
$table->string('customer', 6); // TODO: repalce with uuid
$table->bigInteger('created'); // unix timestamp when created
$table
->bigInteger('status')
->nullable()
->default(null); // null not deleted / unix timestamp when deleted
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down() {
Schema::dropIfExists('tables');
}
};

工厂:

CustomersFactory.php

namespace DatabaseFactories;
use IlluminateDatabaseEloquentFactoriesFactory;
/**
* @extends IlluminateDatabaseEloquentFactoriesFactory<AppModelsCustomers>
*/
class CustomersFactory extends Factory {
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition() {
return [
'id' => $this->faker->unique()->regexify('[A-Za-z0-9]{6}'),
'name' => $this->faker->company(),
'active' => $this->faker->boolean(),
'created' => $this->faker->unixTime(),
'status' => $this->faker->boolean() ? null : $this->faker->unixTime(),
];
}
}

TablesFactory.php

namespace DatabaseFactories;
use AppModelsCustomers;
use IlluminateDatabaseEloquentFactoriesFactory;
/**
* @extends IlluminateDatabaseEloquentFactoriesFactory<AppModelsTables>
*/
class TablesFactory extends Factory {
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition() {
return [
'id' => $this->faker->unique()->regexify('[A-Za-z0-9]{8}'),
'number' => $this->faker->unique()->numberBetween(1, 1000),
'customer' => Customers::factory()->create()->id,
'created' => $this->faker->unixTime(),
'status' => $this->faker->boolean() ? null : $this->faker->unixTime(),
];
}
}

播种机:

customersSeeder.php

namespace DatabaseSeeders;
use AppModelsCustomers;
use IlluminateDatabaseConsoleSeedsWithoutModelEvents;
use IlluminateDatabaseSeeder;
class CustomersSeeder extends Seeder {
/**
* Run the database seeds.
*
* @return void
*/
public function run() {
Customers::factory()
->count(10)
->hasTables(20)
->create();
}
}

TablesSeeder.php

namespace DatabaseSeeders;
use AppModelsTables;
use IlluminateDatabaseConsoleSeedsWithoutModelEvents;
use IlluminateDatabaseSeeder;
class TablesSeeder extends Seeder {
/**
* Run the database seeds.
*
* @return void
*/
public function run() {
//
}
}

DatabaseSeeder.php

namespace DatabaseSeeders;
// use IlluminateDatabaseConsoleSeedsWithoutModelEvents;
use IlluminateDatabaseSeeder;
class DatabaseSeeder extends Seeder {
/**
* Seed the application's database.
*
* @return void
*/
public function run() {
$this->call([CustomersSeeder::class]);
}
}

您的问题是您没有告诉每个模型id不是整数,它是默认的(检查源代码)。

所以把这个添加到两个模型中:

protected $keyType = 'string';
public $incrementing = false;

在这里阅读。

通过检查模型,建议您首先定义表名。

// ========== SPECIFY TABLE TO USE (https://stackoverflow.com/a/51746287/19250775) ========== //
protected $table = "users";

然后你需要定义可填充属性,以便批量分配你的数据库,正如文档所说。

// ========== MASS ASSIGNABLE ATTRIBUTES ========== //
protected $fillable = 
[
'id',
'name',
'email',
];

或者如果你想让每个列都是可填充的,只需添加protected属性。

protected $guarded = [];

相关内容

  • 没有找到相关文章

最新更新