I
I
Igor2016-03-22 02:02:56
Laravel
Igor, 2016-03-22 02:02:56

How to create a separate model for a pivot table in a many-to-many relationship?

I am writing a small project, let it be a library. I am using the `frozennode/laravel-administrator` admin package. The following tables are available: books, offices, book_office. The table book_office, in addition to the fields book_id, office_id, has a field availablethat means the presence of a book in a particular office. I ran into the following problem: the package used for the admin panel does not provide the functionality responsible for interacting with such fields. I read that for these purposes it is better to create an additional. model for the connecting table, and edit the required fields with a separate menu item. The question is, when I create a model and describe its methods, it turns out like this:

class BookOffice extends \Eloquent
{
    /**
     * Model's table
     * 
     * @var string
     */
    protected $table = 'book_office';

    /**
     * @var bool
     */
    public $timestamps = false;

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function book()
    {
        return $this->belongsTo(Book::class, 'book_id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function office()
    {
        return $this->belongsTo(Office::class, 'office_id');
    }

}

But when accessing one or another method, an error is obtained, since by default the models have a property . At the moment, I added a column to the table , but I'm afraid that this is not entirely correct, since my primary key was set to . Can you tell me if there is a solution provided in Laravel for my problem? protected $primaryKey = 'id';
idbook_id + office_id

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question