首页 > 解决方案 > 提交第一篇文章后两个表之间的Laravel关系错误

问题描述

岗位型号:

class Post extends Model
{
    protected $fillable = [
        'name',
        'image',
        'genders_id',
        'categories_id',
        'sizes_id',
        'price'
    ];

    public function category()
    {
        return $this->hasOne(Category::class, 'id');
    }

    public function gender()
    {
        return $this->hasOne(Gender::class, 'id');
    }

    public function size()
    {
        return $this->hasOne(Size::class, 'id');
    }
}

index.blade.php:

@foreach ($posts as $post)
    <td><img src="{{ url('storage/'. $post->image) }}" width="100" height="50"></td>
    <td>{{ $post->name }}</td>
    <td>{{ $post->size->name }}</td>
    <td>{{ $post->category->name }}</td>
    <td>{{ $post->gender->name }}</td>
    <td>{{ $post->price }} $</td>
    <td></td>
    </tbody>
@endforeach

帖子表:

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('genders_id');
        $table->string('sizes_id');
        $table->string('categories_id');
        $table->integer('price');
        $table->string('image');
        $table->timestamps();
    });
}

帖子控制器:

public function store(PostValidation $request)
{
    $image = $request->file('image')->store('image');

    Post::create([
        'name' => $request->name,
        'image' => $image,
        'genders_id' => $request->gender,
        'categories_id' => $request->categories,
        'sizes_id' => $request->size,
        'price' => $request->price
    ]);

    return redirect(route('post.index'));
}

这个问题{{ $post->size->name }} {{ $post->gender->name }} {{ $post->category->name }}在我的第一篇文章之后有效,每当我添加第二篇文章时,它都会给我以下错误:

试图获取非对象的属性“名称”(查看:C:\xampp\htdocs\PracticeOnly\resources\views\posts\index.blade.php){{ $post->size->name }}

标签: phplaraveleloquent

解决方案


尝试更新您的模型,如下所示,您混淆了以下参数的顺序hasOne()

class Post extends Model
{
    protected $fillable = [
        'name',
        'image',
        'genders_id',
        'categories_id',
        'sizes_id',
        'price'
    ];

    public function category()
    {
        return $this->hasOne(Category::class,'categories_id');
    }

    public function gender()
    {
        return $this->hasOne(Gender::class,'genders_id');
    }

    public function size()
    {
        return $this->hasOne(Size::class,'sizes_id');
    }
}

一对多关系的标准命名方案是单数列名:

        'genders_id' => 'gender_id'
        'categories_id' => 'category_id'
        'sizes_id' => 'size_id'

推荐阅读