Laravel 无法显示关系名称而不是 id,即使定义为关系

问题描述 投票:0回答:2

我在 Laravel 应用程序中定义了书籍和作者之间的关系,如下所示:

我的书本模型:

class Book extends Model
{
    use HasFactory;

    protected $table = 'books';

    protected $fillable = [
        'ISBN', 'publisher_id', 'author_id', 'year', 'title', 'price',
    ];

    public function author()
    {
        return $this->belongsTo(Author::class);
    }
}

这是我的 BookController 索引:

public function index()
{
    return view('books.index', [
        'books' => DB::table('books')->paginate(15)
    ]);
}

所以现在我想在我的视图中显示作者姓名而不是author_id:

@foreach ($books as $book)
    <tr>
        <td>{{ $book->author->name }}</td>
    </tr>
@endforeach

但我不断收到错误:

Undefined property: stdClass::$author (View: index.blade.php)
laravel laravel-blade
2个回答
1
投票
'books' => DB::table('books')->paginate(15)

当您使用 db 时,您正在处理查询构建器,而不是雄辩的查询构建器!

您必须使用模型本身并加载关系:

'books' => Book::with(['author'])->paginate(15);

0
投票

在标准模型中创建“书籍”和“标准”之间的关系:

**public function book() {
    return $this->belongsTo(Book::class);
}**

使用DataTables时,准备字段如下:

$data_arr = [];
    foreach ($records as $record) {
        $data_arr[] = [
            'id' => $record->id,
            'book' => $record->book,
            'name' => $record->name,
            'description' => $record->description,
            'action' => view('partials.action_buttons', ['route' => '/standards', 'record' => $record, 'action' => ['edit', 'delete']])->render(),
        ];
    }

使用 StandardController 中的“index”函数渲染数据: (假设standards.index是刀片视图)

public function index(Request $request)
{
    if ($request->ajax()) {
        $standards = Standard::with(['book'])->select('standards.*');

        return datatables()->of($standards)
            ->addColumn('book', function ($row) {
                return $row->book->name ?? 'N/A'; // Replace 'name' with the actual column name for the book title
            })
            ->addColumn('action', function ($row) {
                return view('partials.action_buttons', ['route' => '/standards', 'record' => $row, 'action' => ['edit', 'delete']])->render();
            })
            ->rawColumns(['action'])
            ->make(true);
    }
    return view('admin.standards.index');
}

相应地编辑刀片:

<table class="table tborder" id="standardTable">
            <thead class="table-header">
                <tr>
                    <th>ID</th>
                    <th>BOOK</th>
                    <th>STANDARD</th>
                    <th>DESCRIPTION</th>
                    <th>ACTIONS</th>
                </tr>
            </thead>
        </table>
<script>
    $(document).ready(function () {
        $('#standardTable').DataTable({
            processing: true,
            serverSide: true,
            columns: [
                { data: 'id', name: 'id' },
                { data: 'book', name: 'book' }, 
                { data: 'name', name: 'name' },
                { data: 'description', name: 'description' },
                { data: 'action', sortable: false },
            ],
            ajax: {
                url: "standards/",
                type: 'POST',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
            },
        });

    });
</script>
© www.soinside.com 2019 - 2024. All rights reserved.