如何获取 Laravel belongsTo 关系的所有记录(相关和非相关)?

How to get all records(related and non related) of Laravel belongsTo relationship?

如何从关系中获取所有记录?我的意思不仅是相关记录,还有其他记录。

假设我有一个 post 属于某个类别。如果我想更改此 post 的类别,我需要所有可用类别的列表。我可以从关系中得到这个列表吗?

Post型号:

class Post extends Model
{
    public function category()
    {
        return $this->belongsTo('App\Category');
    }
}

类别模型:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    public function posts()
    {
        return $this->hasMany('App\Post');
    }
}

PostsController 我试过:

$postModel->category->find('all'); // Returns null
$postModel->category->all(); // Returns only the related categories

我知道我可以简单地在 PostsController 中使用类别模型,但我更喜欢使用关系来做到这一点。

如果您觉得必须使用该关系才能找到另一个模型,您可以尝试:

$categories = $post->category()->getRelated()->get();