当前位置: 首页 > 知识库问答 >
问题:

Laravel关联关系,如果不存在则创建

党俊健
2023-03-14

嗨,我是新来的拉威尔,在理解如何建立人际关系方面有点挣扎。我试图在laravel中创建一个基本的restful api,有3个模型

class Book extends Model {
   public function author()
   {
        return $this->belongsTo(Author::class);
   }

   public function categories()
   {
        return $this->belongsToMany('App\Category', 'category_book')
        ->withTimestamps();
   }

}

class Author extends Model
{
    public function books(){
        return $this->hasMany(Book::class);
    }
}

class Category extends Model
{
    public function books()
    {
        return $this->belongsToMany('App\Book', 'category_book')
           ->withTimestamps();
    }
}

表迁移:

Schema::create('books', function (Blueprint $table) {
    $table->engine = "InnoDB";
    $table->increments('id');
    $table->string('ISBN', 32);
    $table->string('title');
    $table->integer('author_id')->unsigned();
    $table->float('price')->default(0);
    $table->timestamps();
});

Schema::create('authors', function (Blueprint $table) {
    $table->engine = "InnoDB";
    $table->bigIncrements('id');
    $table->string('name');
    $table->string('surname');
    $table->timestamps();
});

  Schema::create('categories', function (Blueprint $table) {
    $table->engine = "InnoDB";
    $table->bigIncrements('id');
    $table->string('name');
    $table->timestamps();
}); 

Schema::create('category_book', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->integer('category_id')->unsigned();
    //$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
    $table->integer('book_id')->unsigned();
    //$table->foreign('book_id')->references('id')->on('books')->onDelete('cascade');
    $table->timestamps();
});   

书籍是主要的表格,作者与书籍有一对多的关系。类别与书籍有多对多的关系,因为一本书可以在多个类别中。

books表有一个author_id字段将其链接到author表。还有一个名为category_books的透视表,它包含category_id和book_id,用于将书籍链接到类别。

假设我想创建一个新的图书记录,如果作者存在,则将图书与该作者关联;如果不存在,则我想创建一个新的作者记录,然后将图书与该作者关联?

我也希望能够做同样的事情与类别

我的BookController中有以下内容:

    public function store(Request $request)
    {
        $book = new book;
        $book->title = $request->title;
        $book->ISBN = $request->ISBN;
        $book->price = $request->price;
        $book->categories()->associate($request->category);
        $book->save();

        return response()->json($book, 201);
    }

共有1个答案

夏景同
2023-03-14

首先,排队

$book->categories()->associate($request->category);

当要更新属性To关系时,将使用方法Associates()

其次,如果要关联可能存在或不存在的作者,可以使用first或create方法。

$author = Author::firstOrCreate([
    'name' => $request->author_name,
    'surname' => $request->author_surname
]);
$book->author()->associate($author);

你也可以对分类或书籍做同样的处理。

$category = Category::firstOrCreate([
    'name' => $request->category_name
]);
$book->categories()->attach($category);
$book = Book::firstOrCreate([
    'ISBN' => $request->book_isbn,
    'title' => $request->book_title,
    'price' => $request->book_price
]);
$category->books()->attach($book);

firstOrCreate()的使用在这里有文档记录https://laravel.com/docs/5.8/eloquent#other-创建方法本页有更多关于雄辩的关系方法https://laravel.com/docs/5.8/eloquent-relationships

 类似资料:
  • 我创建了一个自定义的推送()方法,它以级联的方式保存所有模型的关系,并收集实体和子实体详细信息的完整快照用于审计日志。 一切都与belongsTo配合良好,并且有很多关系。我只是这样做: 但问题在于他只有一种关系。它不提供任何方法将相关模型附加到我的根模型而不首先保存它。HasOne关系在Laravel中只有save()方法: 如您所见,它不仅关联,而且保存了模型。为了能够检测字段的所有更改,我的

  • 问题内容: 我很沮丧,我不知道该怎么做。 基本上,我只想创建一个表,但是如果它存在,则需要将其删除并重新创建,而不是将其截断,但是如果不存在,则可以创建它。 有人可以帮忙吗? 谢谢乔治 问题答案: 放在tablename您的发言之前。 该语句将删除该表(如果存在),但如果不存在则不会引发错误。

  • 我试图使用cypher创建一个查询,该查询将“查找”厨师可能有的缺失食材,我的图是这样设置的:

  • 好了,这里是第一次用到NutDao的关联关系了, 打开User类,加入2行 @One(target=UserProfile.class, field="id", key="userId") protected UserProfile profile; 自然的,为其添加Getter/Setter

  • 问题内容: 我正在aws上运行django测试服务器,并且刚刚安装了django-userena,当我尝试单击“提交”以注册用户时,收到以下消息: 关系“ django_site”不存在第1行:…“ django_site”。“域”,“ django_site”。“名称”来自“ django_si … 我不太确定这里出了什么问题。我做了一些研究并将其添加到已安装的应用程序中,但是仍然出现错误。我将

  • 问题内容: 我正在使用PostgreSQL,并且是SQL的初学者。我正在尝试从查询创建表,并且如果运行: 它工作正常。但是然后如果我添加“如果不存在”并运行: 使用完全相同的查询,我得到: 有什么办法吗? 问题答案: CREATE TABLE AS被认为是与普通CREATE TABLE 分开的语句,并且 直到Postgres版本9.5 (请参阅changelog条目)不支持子句 为止 。(请务必查