Laravel-无法使用belongsTo关系保存记录

时间:2017-11-10 08:46:22

标签: laravel foreign-keys laravel-5.3 belongs-to

我有两张桌子

  • 分类
  • 媒体

类别字段

  • ID
  • 名称
  • 描述
  • 缩略图
  • 横幅

媒体字段

  • ID
  • 标题

我想要做的是,每当我创建新类别时,在上传缩略图和横幅之后,将在媒体表中为它们创建新记录,并且这些记录的ID将针对特定类别存储。

每种媒体只属于一个类别,一个类别只有两个媒体。

类别中的缩略图和横幅广告将存储来自媒体的媒体ID。

这是我的代码

$category = Category::create($input);
$media = Media::create([
          'title'  => $photoName,
          'source' => $photoName,
        ]);

$类别 - >媒体 - >附加($媒体 - > ID);

类别模型

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

媒体模型

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

任何人都可以帮助我解决我在这里做错的事情

理解的,

2 个答案:

答案 0 :(得分:0)

我希望你需要检查你的表,因为这两个表都没有关系。如果您这样做,那么您的代码将起作用

您应该在laravel 5.4中使用这些表模式

        Schema::create('Category', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name')->unique();
        $table->string('description')->nullable();
        $table->string('thumbnail')->nullable();
        $table->string('banner')->nullable();
        $table->timestamps();
    });

    // Create table for associating roles to users (Many-to-Many)
    Schema::create('Media', function (Blueprint $table) {
        $table->integer('id')->unsigned();
        $table->integer('category_id')->unsigned();
        $table->string('title')->nullable();
        $table->string('source')->nullable();

        $table->foreign('category_id')->references('id')->on('Category')
            ->onUpdate('cascade')->onDelete('cascade');

        $table->primary(['id', 'category_id']);
    });

答案 1 :(得分:0)

您应该将外键添加到“类别”字段中:

 id,media_id,name,description,thumbnail,banner

现在你可以使用relatioship:

$category = Category::findOrFail(1);    // get category with id = 1 
$media = Media::create([
          'title'  => $photoName,
          'source' => $photoName,
        ]);
$category->media()->associate($media);

了解更多信息: https://laravel.com/docs/5.5/eloquent-relationships#one-to-one

相关问题