【问题标题】:Laravel-8 one-many/many-one relationshipLaravel-8 一对多/多一关系
【发布时间】: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-&gt;category_id)-&gt;categories()-&gt;first();。这将找到第一个Entry,它有一个category_id,比如说1(JavaScript),然后你正在访问那个Entry的所有Category记录并获取第一个Category,这可能是每次都一样...这根本没有多大意义...

标签: php laravel eloquent laravel-8


【解决方案1】:

您正在获取category_id 的条目,无需再次查找Entry

$category = Entry::find($entry->category_id)->categories()->first();

应该是

$category = $entry->category;

BelongsTo是一个奇异的关系,可以描述如下。

public function category() {
    return $this->belongsTo(Category::class);
}

【讨论】:

    猜你喜欢
    • 2018-06-15
    • 2017-12-24
    • 2018-09-27
    • 2018-03-16
    • 2018-04-20
    • 1970-01-01
    相关资源
    最近更新 更多