【发布时间】:2021-03-01 02:07:24
【问题描述】:
我正在尝试为每个条目的页面显示类别,但它们都只显示“JavaScript”。
(一个类别可以有多个条目,但每个条目只有一个类别。)
我的类别模型:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = 'categories';
protected $fillable = [
'name'
];
public function entries() {
return $this->hasMany(Entry::class);
}
}
我的条目模型:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Entry extends Model
{
protected $table = 'entries';
protected $fillable = [
'title',
'hours',
'minutes',
'category_id',
'difficulty',
'url'
];
public function categories() {
return $this->belongsTo(Category::class, 'category_id');
}
public function getCreatedAtAttribute($value)
{
return date('F d, Y H:i', strtotime($value));
}
}
我的 EntryController 的 show() 方法:
/**
* Display the specified resource.
*
* @param Entry $entry
* @return \Illuminate\Http\Response
*/
public function show(Entry $entry)
{
$category = Entry::find($entry->category_id)->categories()->first();
return view( 'entries.show', compact( 'entry', 'category' ) );
}
我的分类表的 up() 方法:
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name', 255);
});
}
我的条目表的 up() 方法:
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('entries', function (Blueprint $table) {
$table->id();
$table->string('title', 255);
$table->timestamps();
$table->integer('hours');
$table->integer('minutes');
$table->foreignId('category_id')->constrained('categories');
$table->string('difficulty', 255);
$table->string('url', 255);
});
Schema::enableForeignKeyConstraints();
}
【问题讨论】:
-
你在这里做什么:
$category = Entry::find($entry->category_id)->categories()->first();。这将找到第一个Entry,它有一个category_id,比如说1(JavaScript),然后你正在访问那个Entry的所有Category记录并获取第一个Category,这可能是每次都一样...这根本没有多大意义...
标签: php laravel eloquent laravel-8