dsxz84851 2018-06-01 14:36 采纳率: 100%
浏览 19

使用Ajax输入在Laravel中创建透视表值

I'm learning Laravel by creating a recipe website.

The idea is a user creates a recipe which includes a title, description and number of portions (and tags), and then is directed to a new view in which they add the ingredients.

I've got this working, and the user can successfully create the recipe and the ingredients, which are being written to their respective tables, but I'm unable to attach/sync them.

Relevant parts of the models:

Recipe Model:

class Recipe extends Model
{
  public function ingredients(){
    return $this->hasMany('App\Ingredient', 'recipe_ingredients');
  }
}

Ingredient Model:

class Ingredient extends Model
{

  public function recipe(){
    return $this->belongsTo('App\Recipe', 'recipe_ingredients');
  }
}

Ingredients Controller

public function store(Request $request)
{

  $this->validate($request, [
    'name' => 'required|max:255'
  ]);

  $ingredient = new Ingredient;
  $ingredient->name = $request->name;
  $ingredient->save();

  $recipe = Recipe::find($request->id);

  $recipe->ingredients()->attach($recipe_id);

  $data = [
    'success' => true,
    'message'=> 'Your AJAX processed correctly',
    'name' => $ingredient->name,
    'recipe' => $recipe
  ] ;

    return response()->json($data);
}

If I remove the $recipe->ingredients()->attach($recipe_id); the ingredients save to the ingredients table, but I can't get the recipe_id and ingredient_id to save in the recipe_ingredients table`.

I think I'm using the attach wrong, but I could be wrong.

Note: Not that I think it makes any difference, but I'm submitting the data via Ajax.

Script:

$(document).ready(function(){
  $("#submit").click(function() {
    var name = $("#ingredientName").val();
    var token = $("#token").val();

    $.ajax({
      headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
      type: "post",
      data: "name="+name,
      dataType:'json',
      url: "{{ route('ingredients.store', ['id' => $recipe->id]) }}",
      success:function(data){
        console.log(data);
        $("#msg").html('<div class="alert alert-success my-0">'+data.name+' added</div>');
        $("#msg").toggleClass("invisible")
        $("#msg").fadeOut(2000);
        $("#ingredientsTable").append('<tr><td scope="col" class="align-middle">'+data.name+'</td></tr>');
      }
    });
  })
})

Revised Controller

public function store(Request $request)
{

  $this->validate($request, [
    'name' => 'required|max:255'
  ]);

  $ingredient = new Ingredient;
  $ingredient->name = $request->name;
  $ingredient->save();

  $recipe = Recipe::find($request->id);
  $recipe->ingredients()->attach($ingredient->id);

  $data = [
    'success' => true,
    'message'=> 'Your AJAX processed correctly',
    'name' => $ingredient->name,
    'recipe' => $recipe
  ] ;

    return response()->json($data);
}

Table migration

public function up()
{
    Schema::create('recipe_ingredients', function (Blueprint $table) {
        $table->integer('recipe_id')->unsigned();
        $table->foreign('recipe_id')->references('id')->on('recipes');

        $table->integer('ingredient_id')->unsigned();
        $table->foreign('ingredient_id')->references('id')->on('ingredients');
    });
}
  • 写回答

3条回答 默认 最新

  • duanmou9228 2018-06-01 14:40
    关注

    As shown by the example here: https://laravel.com/docs/5.6/eloquent-relationships#updating-many-to-many-relationships

    You should be attaching the ingredients instead of the recipe:

    $recipe->ingredients()->attach($ingredient_id);

    -- edit --

    You also have your Ingredient model as:

    class Ingredient extends Model
    {
      public function ingredient(){
          return $this->belongsToMany('App\Recipe', 'recipe_ingredients');
      }
    }
    

    However, you should have this instead:

    public function recipes(){
        return $this->belongsToMany('App\Recipe', 'recipe_ingredients');
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图