【问题标题】:Laravel 5.4 transaction and one-many relationLaravel 5.4 事务和一对多关系
【发布时间】:2018-06-15 17:38:57
【问题描述】:

我刚开始使用 laravel,但我被困在这一点上,我没有找到办法

基本上我会插入带有类别的文章。

使用 select2,我选择一个现有类别或创建一个新类别。

我的文章模型:

public function category(){
    return $this->belongsTo('App\Category');
}

我的类别模型:

public function articles(){
    return $this->hasMany('App\Article');
}

我的文章迁移:

public function up()
{
    Schema::create('articles', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->longText('content')->nullable();
        $table->timestamps();
    });
}

我的分类迁移:

Schema::create('categories', function (Blueprint $table) {
        $table->increments('id');
        $table->string('nom')->unique();
    });

    Schema::table('articles', function(Blueprint $table){
        $table->integer('category_id')->unsigned()->index();
    });

最后是我的控制器功能来存储文章(我想使用事务):

public function store(Request $request)
{
    $this->validate($request, [
        'numero' => 'required',
        'category' => 'required',
        'title' => 'required'
    ]);
    $article = new Article();
    DB::transaction(function() use ($request) {
       $category = Category::firstOrCreate(['nom' => $request->input('category')]);
       $article->title = $request->input('title');
       $article->save();
    });
    return response()->json([
        'title' => $article->title
    ]);
}

所以我知道我没有将类别 ID 保存到文章数据库中,但我的类别甚至没有插入,在我的调试栏上我有这个:

开始交易 select * from batiments where (nom = 'HI') 限制 1 回滚事务

我的帖子页面给了我这个错误:

SQLSTATE[23000]: 完整性约束违规: 1062 Duplicata du champ '' pour la clef 'batiments_nom_unique' (SQL: insert into batiments () values ())

有人知道如何插入或选择如果存在类别并将id插入到文章表中?

谢谢

【问题讨论】:

  • articles 表应该包含category_id 字段,并且迁移文件中的关系应该在文章迁移中而不是在类别迁移中。

标签: php mysql laravel


【解决方案1】:

$table->integer('category_id')->unsigned()->index();

您将此字段设置为索引,只需删除 index()。身份字段必须只有唯一记录,但您的 category_id 可能多次具有相同的值。

【讨论】:

  • 噢噢对了!谢谢 !其余的代码是正确的方法吗?
  • 是的,没有其他问题
【解决方案2】:

代码:

$table->integer('categorie_id')->unsigned(); 

$table->foreign('categorie_id')->references('id')->on('categories');

Laravel 支持创建外键约束,用于在数据库级别强制引用完整性。例如,让我们在 items 表上定义一个 categorie_id 列,它引用 categories 表上的 id 列 laravel.com/docs/5.4/migrations#foreign-key-constraints

【讨论】:

  • 请补充说明
  • Laravel 支持创建外键约束,用于在数据库级别强制引用完整性。例如,让我们在文章表上定义一个 categorie_id 列,它引用类别表上的 id 列:laravel.com/docs/5.4/migrations#foreign-key-constraints
  • 将此添加到您的答案中,而不是评论中
  • 我的做法不对?我在一篇文章中找到了这个:/
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-27
  • 2018-01-22
  • 2018-06-16
  • 2023-03-09
  • 2016-03-02
  • 2018-06-15
相关资源
最近更新 更多