在 returns Laravel 中的模型的方法上访问 属性

Accessing a property on a method which returns a Model in Laravel

我有一个 Post 模型,其功能如下:

namespace App;

use App\Category;

class Post extends Model

{
    public function category()
   {

    return $this->hasOne(Category::class);

   }

}

我的类别模型如下所示

namespace App;

use App\Post;

class Category extends Model
{
    public function posts()
    {

    return $this->hasMany(Post::class);

    }
}

在我看来,我想访问每个 post.

类别中的 name 字段

我假设我可以访问该模型,因此可以通过在我的 blade 文件中这样做来获得它:

{{ $post->category()->name }}

$post 是正确的,我可以访问其他属性,但这会引发错误:

Undefined property: Illuminate\Database\Eloquent\Relations\HasOne::$name

有什么想法吗?

您应该将其作为属性访问:

{{ $post->category->name }}

函数 category() 应在 Post 模型中定义为:

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

如果category_id有其他名称,只需在参数中更改即可。

您可以轻松做到这一点:

$category=$post->category;
$cat_name=$category->name;

另外,如果您只想要类别的名称字段,您可以使用:

$cat_name=$post->category()->get(['name']);