Я рассмотрел несколько похожих проблем на SO, но я не могу понять, почему вызываются рецепты?
Я создаю веб-сайт с рецептами, и пользователь может создавать теги, создавать рецепты, создавать ингредиенты, которые назначаются рецепту, и иметь возможность создавать шаги, в которых используются ингредиенты.
Следующие мои модели:
Ingredient.php
class Ingredient extends Model
{
protected $touches = ['recipes'];
public function recipes(){
return $this->belongsToMany('App\Recipe', 'recipe_ingredients', 'ingredient_id', 'recipe_id');
}
public function step(){
return $this->belongsToMany('App\Step', 'step_ingredients');
}
}
Recipe.php
class Recipe extends Model
{
public function ingredients(){
return $this->belongsToMany ('App\Ingredient', 'recipe_ingredients', 'recipe_id', 'ingredient_id');
}
public function tags(){
return $this->belongsToMany('App\Tag', 'recipe_tag');
}
public function user(){
return $this->belongsTo('App\User');
}
public function steps(){
return $this->hasMany('App\Step');
}
}
Step.php
class Step extends Model
{
protected $touches = ['recipes'];
public function recipe(){
return $this->belongsTo('App\Recipe');
}
public function ingredient(){
return $this->belongsToMany('App\Ingredient', 'step_ingredient');
}
}
Ниже приведен мой StepsController, который я сохраняю из моего файла шаги / create.blade.php через отправку Ajax с помощью jQuery.
use Illuminate\Http\Request;
//use Session;
use App\Recipe;
use App\Tag;
use App\Step;
use App\Ingredient;
class StepsController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function create($recipe_id)
{
$recipe = Recipe::find($recipe_id);
return view('steps.create')->withRecipe($recipe);
}
public function store(Request $request)
{
$step = new Step;
$step->recipe_id = 2;
$step->step_no = 2;
$step->is_prep = 1;
$step->duration = '00:14:01';
$step->method = 'test';
$step->save();
$data = [
'success' => true,
'message'=> 'Your AJAX processed correctly',
'ing' => json_decode($request->ingredients),
'desc' => $request->description
] ;
return response()->json($data);
}
}
Я использую статические значения для new Step, чтобы убедиться, что он правильно записывает в базу данных, и это так.
Если я закомментирую запись шага в базу данных и просто оставлю массив $data и return response..., тогда он будет работать нормально, и я получу ответ успеха, возвращенный в представление.
При включении в консоли появляется ошибка:
[Error] Failed to load resource: the server responded with a status of 500 (Internal Server Error) (steps, line 0)
"message": "Method Illuminate\\Database\\Query\\Builder::recipes does not exist.",
Но я не уверен, что где вызывается метод recipes ?! Я думаю, это как-то связано с моими отношениями в модели?
Любое понимание было бы очень признательно.
Не уверен, требуется ли это, но я использую следующую часть моего сценария, поэтому отправляйте данные с помощью Ajax.
$("#addStepNew").click(function() {
var step_ingredients = JSON.stringify(stepIngredients)
var step_description = $('#stepDescription').val();
// var prep_step = $('input[name=prepStep]:checked').val();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name = "csrf-token"]').attr('content')
},
type: "post",
data: {ingredients: step_ingredients, description: step_description},
dataType:'json',
url: "{{ route('steps.store', ['id' => $recipe->id]) }}",
success: function (data) {
$("#ajaxOutput").html('<code>Description output: '+data.desc+'</code>');
$.each(data.ing, function (key, value) {
$("#ajaxOutput").append('<br><code>'+value.ingredient_name+'</code>');
});
},
error: function (xhr, ajaxOptions, thrownError) {
console.warn(xhr.responseText);
alert(xhr.status);
alert(thrownError);
}
});
});






Похоже, это protected $touches = ['recipes']; от модели Step.
Я предполагаю, что он пытается обновить рецепт, с которым он связан, но это не определено с recipe_id.