首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将透视数据返回到Laravel中的视图

将透视数据返回到Laravel中的视图
EN

Stack Overflow用户
提问于 2018-06-03 03:54:09
回答 1查看 825关注 0票数 0

我不太确定我到底做错了什么。

我有一个正在学习的recipe项目,但我似乎无法将数据通过数据透视表连接到视图中。

用户创建一个食谱[at (名称,描述,部分,标签等),然后被引导到“创建配料”视图。从这里开始,他们通过Ajax请求和recipe_ingredients.中的链接添加配料,该请求已成功保存到配料表中

我通过ajax动态地将配料添加到表中,但是当用户刷新页面时,我需要它遍历配料表,并且只返回与给定食谱相关联的配料。

我使用了以下循环,但它不起作用:

代码语言:javascript
复制
@foreach($recipe->ingredients as $ingredient)
  {{$recipe->ingredient->name}}
@endforeach

我得到了以下错误:

代码语言:javascript
复制
ErrorException (E_ERROR):
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'ingredients.recipe_ingredients' in 'where clause' (SQL: select * from `ingredients` where `ingredients`.`recipe_ingredients` is null and `ingredients`.`recipe_ingredients` is not null) (View: C:\xampp\htdocs\sites\recipes\resources\views\ingredients\create.blade.php)

信息:

我有3个表:recipesingredientsrecipe_ingredients

配方模型:

代码语言:javascript
复制
class Recipe extends Model
{
  public function ingredients(){
    return $this->hasMany('App\Ingredient', 'recipe_ingredients', 'recipe_id', 'ingredient_id');
  }

成分模型:

代码语言:javascript
复制
class Ingredient extends Model
{
    public function recipes(){
    return $this->belongsToMany('App\Recipe', 'recipe_ingredients', 'ingredient_id', 'recipe_id');
}

配料控制器

代码语言:javascript
复制
public function create($recipe_id)
{
  $recipe = Recipe::find($recipe_id);
  return view('ingredients.create')->withRecipe($recipe);
}

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);
  $ingredient->recipes()->attach($recipe->id);

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

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

用于将配料保存到db:的Ajax脚本

代码语言:javascript
复制
<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>');
      }
    });
  })
})
</script>

视图的相关部分:

代码语言:javascript
复制
<div class="row">
  <div class="col-lg-3">
    <div class="card">
      <div class="card-body">
        <!-- 
        <p><b>Est. prep time:</b></p>
        <p><b>Est. cooking time:</b></p>
        -->
        <p><b>Portions:</b> {{ $recipe->portions }}</p>
        <p><b>Creator:</b> <a href="#">{{ $recipe->user->name }}</a></p>
        @if($recipe->created_at == $recipe->updated_at) 
          <p><b>Created:</b> {{ $recipe->created_at->diffForHumans() }}</p>
        @else
          <p><b>Updated:</b> {{ $recipe->updated_at->diffForHumans() }}</p>
        @endif
        <!-- 
        <p><b>Rating:</b> <i class="fas fa-star"></i><i class="fas fa-star"></i><i class="fas fa-star"></i><i class="fas fa-star"></i><i class="fas fa-star-half"></i>&nbsp;(52)</p>
        -->

        <div id="tags">
          @foreach($recipe->tags as $tag)
            <button type="button" class="btn btn-outline-{{$tag->colour}} btn-sm my-1">{{$tag->name}}</button>
          @endforeach
        </div>

      </div>
    </div>
  </div>

  <div class="col-lg-9">
    <table class="table table-hover table-light" style="border: 1px solid rgba(0,0,0,.125);">
      <thead>
        <tr>
          <th scope="col">Ingredients:</th>
        </tr>
      </thead>
      <tbody id="ingredientsTable">

        @foreach($recipe->ingredients as $ingredient)
        {{$recipe->ingredient->name}}
        @endforeach
      </tbody>
    </table>
  </div>
</div>

路由:

代码语言:javascript
复制
$ php artisan route:list
+--------+-----------+--------------------------+--------------------+------------------------------------------------------------------------+--------------+
| Domain | Method    | URI                      | Name               | Action                                                                 | Middleware   |
+--------+-----------+--------------------------+--------------------+------------------------------------------------------------------------+--------------+
|        | GET|HEAD  | /                        |                    | App\Http\Controllers\PagesController@index                             | web          |
|        | GET|HEAD  | api/user                 |                    | Closure                                                                | api,auth:api |
|        | GET|HEAD  | home                     | home               | App\Http\Controllers\HomeController@index                              | web,auth     |
|        | GET|HEAD  | login                    | login              | App\Http\Controllers\Auth\LoginController@showLoginForm                | web,guest    |
|        | POST      | login                    |                    | App\Http\Controllers\Auth\LoginController@login                        | web,guest    |
|        | POST      | logout                   | logout             | App\Http\Controllers\Auth\LoginController@logout                       | web          |
|        | POST      | password/email           | password.email     | App\Http\Controllers\Auth\ForgotPasswordController@sendResetLinkEmail  | web,guest    |
|        | GET|HEAD  | password/reset           | password.request   | App\Http\Controllers\Auth\ForgotPasswordController@showLinkRequestForm | web,guest    |
|        | POST      | password/reset           |                    | App\Http\Controllers\Auth\ResetPasswordController@reset                | web,guest    |
|        | GET|HEAD  | password/reset/{token}   | password.reset     | App\Http\Controllers\Auth\ResetPasswordController@showResetForm        | web,guest    |
|        | POST      | recipes                  | recipes.store      | App\Http\Controllers\RecipesController@store                           | web,auth     |
|        | GET|HEAD  | recipes                  | recipes.index      | App\Http\Controllers\RecipesController@index                           | web,auth     |
|        | GET|HEAD  | recipes/create           | recipes.create     | App\Http\Controllers\RecipesController@create                          | web,auth     |
|        | GET|HEAD  | recipes/{id}/ingredients | ingredients.create | App\Http\Controllers\IngredientsController@create                      | web,auth     |
|        | POST      | recipes/{id}/ingredients | ingredients.store  | App\Http\Controllers\IngredientsController@store                       | web,auth     |
|        | GET|HEAD  | recipes/{recipe}         | recipes.show       | App\Http\Controllers\RecipesController@show                            | web,auth     |
|        | DELETE    | recipes/{recipe}         | recipes.destroy    | App\Http\Controllers\RecipesController@destroy                         | web,auth     |
|        | PUT|PATCH | recipes/{recipe}         | recipes.update     | App\Http\Controllers\RecipesController@update                          | web,auth     |
|        | GET|HEAD  | recipes/{recipe}/edit    | recipes.edit       | App\Http\Controllers\RecipesController@edit                            | web,auth     |
|        | POST      | register                 |                    | App\Http\Controllers\Auth\RegisterController@register                  | web,guest    |
|        | GET|HEAD  | register                 | register           | App\Http\Controllers\Auth\RegisterController@showRegistrationForm      | web,guest    |
|        | POST      | steps                    | steps.store        | App\Http\Controllers\StepsController@store                             | web,auth     |
|        | GET|HEAD  | steps                    | steps.index        | App\Http\Controllers\StepsController@index                             | web,auth     |
|        | GET|HEAD  | steps/create             | steps.create       | App\Http\Controllers\StepsController@create                            | web,auth     |
|        | GET|HEAD  | steps/{step}             | steps.show         | App\Http\Controllers\StepsController@show                              | web,auth     |

迁移:

create_recipes_table

代码语言:javascript
复制
Schema::create('recipes', function (Blueprint $table) {
  $table->increments('id');
  $table->string('name');
  $table->text('description');
  $table->integer('portions');
  $table->integer('user_id');
  $table->timestamps();
});

create_ingredients_table

代码语言:javascript
复制
Schema::create('ingredients', function (Blueprint $table) {
    $table->increments('id');
    $table->text('name');
    $table->boolean('approved')->nullable();
    $table->datetime('approved_at')->nullable();
    $table->integer('approved_by')->nullable();
    $table->timestamps();
});

create_recipe_ingredients_table

代码语言:javascript
复制
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');
});
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-03 04:06:39

您得到此错误是因为您的配方模型上的关系不正确。由于配方和梯度之间的关系是多对多的,因此两个模型都需要与另一个模型具有belongsToMany关系:

代码语言:javascript
复制
class Recipe extends Model
{
    public function ingredients(){
        return $this->belongsToMany('App\Ingredient', 'recipe_ingredients');
    }
}

您的foreach中也有一个错误,您应该引用循环中的$ingredient

代码语言:javascript
复制
@foreach($recipe->ingredients as $ingredient)
  {{ $ingredient->name }}
@endforeach
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50660640

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档