我尝试为每个条目的页面显示类别,但它们都只显示‘JavaScript’。
(一个类别可以有多个条目,但每个条目只有一个类别。)
我的Category模型:
<?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' ) );
}我的categories表的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();
}发布于 2020-11-18 04:00:51
您正在通过category_id获取条目,不需要再次查找Entry。
$category = Entry::find($entry->category_id)->categories()->first();应该是
$category = $entry->category;BelongsTo是一种奇异关系,可以这样描述。
public function category() {
return $this->belongsTo(Category::class);
}https://stackoverflow.com/questions/64882360
复制相似问题