在laravel 5.2中使用工厂关系违反完整性约束

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在laravel 5.2中使用工厂关系违反完整性约束相关的知识,希望对你有一定的参考价值。

我是laravel测试的新手,我正在尝试使用Model Factories创建虚拟数据。我有三张桌子:

  • 公司
  • 客户
  • 内裤

公司有很多客户,客户有很多简报。 clientsbriefs的格式非常相似。他们恭敬地拥有外键firm_idclient_id。在进行phpunit测试时,我想使用以下代码从公司创建客户端实例和客户端的简介实例:

$client = $firm->clients()
               ->save(factory(AppSearchFirmClient::class)->create());
$brief  = $client->briefs()
                 ->save(factory(AppSearchFirmBrief::class)->create());

$client创建没有大惊小怪,但$brief抛出一个错误:

IlluminateDatabaseQueryException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'client_id' cannot be null (SQL: insert into `search_firms_briefs` (`user_id`, `title`, `description`, `contact_id`, `client_id`, `updated_at`, `created_at`) values (1, Et in amet., Quo soluta ut impedit nesciunt autem. Laborum aperiam est non molestiae animi non quod. Explicabo eligendi doloribus ex quia vitae placeat ut., 0, , 2016-03-30 10:06:34, 2016-03-30 10:06:34))

两个表的格式:

Schema::create('search_firms_clients', function(Blueprint $table)
{
    $table->increments('client_id');
    $table->integer('search_firm_id')->unsigned();
    $table->foreign('search_firm_id')->references('id')->on('search_firms')->onDelete('cascade');           
    $table->string('name');
    $table->softDeletes();
    $table->timestamps();
});

Schema::create('search_firms_briefs', function(Blueprint $table)
{
    $table->increments('brief_id');
    $table->integer('client_id')->unsigned();
    $table->foreign('client_id')->references('client_id')->on('search_firms_clients')->onDelete('cascade');         
    $table->string('title');
    $table->softDeletes();
    $table->timestamps();
});

每个模型工厂:

$factory->define(AppSearchFirmClient::class, function ($faker) {
    return [
        'name'      => $faker->company,
        'email'     => $faker->companyEmail,
        'phone'     => $faker->phoneNumber,
        'address'   => $faker->address,
        'website'   => $faker->url,
    ];
});

$factory->define(AppSearchFirmBrief::class, function ($faker) {
    return [
        'user_id'       => 1,
        'title'         => $faker->sentence(3),
        'description'   => $faker->text(),
        'contact_id'    => 0,
    ];
});

关系:

class SearchFirm extends Model
{

    protected $table = 'search_firms';
    protected $primaryKey = 'id';

    public function clients() {
        return $this->hasMany('SearchFirmClient', 'search_firm_id');
    }
}

class SearchFirmClient extends Model
{

    use SoftDeletes;

    protected $table        = 'search_firms_clients';
    protected $primaryKey   = 'client_id';
    protected $dates        = [ 'deleted_at' ];


    public function briefs()
    {
        return $this->hasMany('SearchFirmBrief', 'client_id')->orderBy( 'updated_at', 'desc');
    }
}

class SearchFirmBrief extends Model
{

    use SoftDeletes;

    protected $table = 'search_firms_briefs';
    protected $primaryKey = 'brief_id';
    protected $touches = array('client');
    protected $dates = [ 'deleted_at'];

    public function client() {
        return $this->belongsTo('SearchFirmClient', 'client_id');
    }
}
答案

问题#1

id表上没有briefs列,但是您在clients表上引用它。

将外键更改为brief_id

Schema::create('search_firms_clients', function(Blueprint $table)
{
    $table->increments('client_id');
    $table->integer('search_firm_id')->unsigned();
    $table->foreign('search_firm_id')
          ->references('brief_id') // <-- Change this
          ->on('search_firms')
          ->onDelete('cascade');           
    $table->string('name');
    $table->softDeletes();
    $table->timestamps();
});

Schema::create('search_firms_briefs', function(Blueprint $table)
{
    $table->increments('brief_id');
    $table->integer('client_id')->unsigned();
    $table->foreign('client_id')->references('client_id')->on('search_firms_clients')->onDelete('cascade');         
    $table->string('title');
    $table->softDeletes();
    $table->timestamps();
});

问题#2

你没有user_id会员。

$factory->define(AppSearchFirmBrief::class, function ($faker) {
    return [
        'client_id'     => 1, // <-- change this
        'title'         => $faker->sentence(3),
        'description'   => $faker->text(),
        'contact_id'    => 0,
    ];
});

结论

最好遵循Laravel的命名标准,它将在未来为您节省很多麻烦(即使用默认表名,主键名)

以上是关于在laravel 5.2中使用工厂关系违反完整性约束的主要内容,如果未能解决你的问题,请参考以下文章

SQLSTATE[23000]:违反完整性约束:在 Laravel 5.2 中

使用 Laravel ORM 抽象保存新的不可为空的关系,而不会违反数据库完整性约束

Laravel 5.2:无法找到具有名称的工厂 [默认]

Laravel 删除(违反完整性约束)

laravel 8 播种,SQLSTATE[23000]:违反完整性约束:

Laravel 迁移 - 违反完整性约束:1452 无法添加或更新子行:外键约束失败