Answer the question
In order to leave comments, you need to log in
How to make hasMany work in Laravel BackPack?
I'm trying to connect the BackPack admin panel to the project, when using the hasMany connection, a bunch of errors come out, it can't find the fields, then there is no method ...
App\Models\Question
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Backpack\CRUD\app\Models\Traits\CrudTrait;
class Question extends Model{
use CrudTrait;
public function answers() {
return $this->hasMany(\App\Models\Answer::class);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Backpack\CRUD\app\Models\Traits\CrudTrait;
class Answer extends Model{
use CrudTrait;
public function question() {
return $this->belongsTo(\App\Models\Question::class, 'question_id');
}
}
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Requests\QuestionRequest;
use Backpack\CRUD\app\Http\Controllers\CrudController;
use Backpack\CRUD\app\Library\CrudPanel\CrudPanelFacade as CRUD;
class QuestionCrudController extends CrudController{
use \Backpack\CRUD\app\Http\Controllers\Operations\ListOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\CreateOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\UpdateOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\DeleteOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\ShowOperation;
public function setup() {
$this->crud->setModel('App\Models\Question');
$this->crud->setRoute(config('backpack.base.route_prefix') . '/question');
$this->crud->setEntityNameStrings('Вопрос', 'Вопросы');
}
protected function setupUpdateOperation() {
$this->setupCreateOperation();
$this->crud->addField([ // Select2Multiple = n-n relationship (with pivot table)
'label' => "Ответы",
'type' => 'select2_multiple',
'name' => 'answers', // the method that defines the relationship in your Model
'entity' => 'question', // the method that defines the relationship in your Model
'attribute' => 'title',
'model' => "App\Models\Answer",
]);
}
}
Answer the question
In order to leave comments, you need to log in
Use hasOne and BelongsToMany (just the opposite, a question doesn't have many answers, one question belongs to many answers).
I myself had such a problem, I did not understand what it was connected with, but it only works in this direction.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question