принадлежит и имеет много отношений в laravel - PullRequest
0 голосов
/ 06 октября 2019

У меня три таблицы книг, Категория и авторы, даже после создания отношений между ними я получаю только идентификатор, а не Имя. Я видел много ссылок, но не понял, в чем проблема с моим кодом

Модель моих книг

class books extends Model
{
    //
    protected $table='books';
    protected $primarykey = 'bookId';

    public function books_categories(){
        return $this->belongsTo('app\books_categories', 'catId', 'catId');
    }

    public function authors(){
        return $this->belongsTo('app\authors','authId','authId');
    }
}

Мои авторы Модель

class authors extends Model
{
    //
    public function books(){
        return $this->hasMany('app\books','authId','authId');
    }
}

Мои книги_категорииМодель

class books_categories extends Model
{
    //
    public function books(){
        return $this->hasMany('app\books');
    }
}

Таблица моих книг

    public function up()
    {
        Schema::create('books', function (Blueprint $table) {
            $table->increments('bookId');
            $table->string('bookTitle', 255)->nullable('false');
            $table->unsignedInteger('edition');
            $table->unsignedInteger('authId');
            $table->unsignedInteger('catId');
            $table->foreign('catId')->references('catId')->on('books_categories');
            $table->foreign('authId')->references('authId')->on('authors');
            $table->unsignedInteger('totalAvail')->default(0);
            $table->unsignedInteger('totalIss')->default(0);
            $table->timestamps();
        });
    }

Мой контроллер

    public function index()
    {
        $books = books::all();
        return view('booksList', ['books'=> $books]);

    }

My View

<div class="panel panel-default">
    <div class="panel-heading">Books List</div>
    <div class="panel-body">
        <table class="table table-hover table-bordered">
            <thead>
            <tr>
                <th scope="col">BookID</th>
                <th scope="col">Title</th>
                <th scope="col">Edition</th>
                <th scope="col">Category</th>
                <th scope="col">Author</th>
                <th scope="col">Books Available</th>
                <th scope="col">Action</th>

            </tr>
            </thead>
            <tbody>

            @foreach($books as $book)
                <tr>
                    <td>{{$book->bookId}}</td>
                    <td>{{$book->bookTitle}}</td>
                    <td>{{$book->edition}}</td>
                    <td>{{$book->catId}}</td>
                    <td>{{$book->authId}}</td>
                    <td>{{$book->totalAvail}}</td>
                    <td>
                        <span><button type="button" class="btn btn-primary btn-xs"><i class="glyphicon glyphicon-edit"></i></button></span>
                        <span><button type="button" class="btn btn-primary btn-xs"><i class="glyphicon glyphicon-trash"></i></button></span>

                    </td>
                </tr>
        @endforeach
            </tbody>
        </table>
    </div>
</div>

enter image description here Как получить имя вместо ID

Ответы [ 2 ]

3 голосов
/ 07 октября 2019

Он показывает идентификатор, потому что вы говорите, чтобы он показал, что, написав <td>{{$book->authId}}</td>

, измените его на

<td>{{$book->authors->name}}</td>

, измените name, чтобы оно соответствовало имени вашего атрибутав вашей базе данных.

обратитесь к официальным документам здесь для получения более подробной информации о том, как обрабатывать Eloquent отношений

https://laravel.com/docs/6.x/eloquent-relationships#one-to-many-inverse

0 голосов
/ 07 октября 2019

Я понял, на самом деле в моем коде было две ошибки 1. Я изменяю свой взгляд с <td>{{$book->authId}}</td> на этот <td>{{$book->authors->name}}</td>, а в модели моих книг я изменил

    public function authors(){
        return $this->belongsTo('app\authors','authId','authId');
    }

на этот

    public function authors(){
        return $this->belongsTo(authors::class,'authId','authId');
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...