我有两个表,posts 表和 categories 表。
每个帖子只有一个类别。
What I am trying to do
在没有外键的情况下将每个帖子与一个类别 ID 连接起来。
Why I am trying to do this
因为我不想在每篇文章中都复制类别词,所以我只想复制类别 ID。
PostsController.php code
$posts = Post::orderBy('id', 'DESC') -> limit(16) -> get();
@foreach($posts as $post)
dd($post -> categories() -> cat);
@endforeach
Posts.php model code
class Post extends Model
{
public function category() {
return $this->hasOne('App\Category');
}
}
Problem
当我在类别表中没有外键时,我收到一个错误要求我提供外键。
最佳答案
FK关系不是必须的。如果你有办法告诉 Laravel 如何查找相关记录,它可以为你做。例如
class Post extends Model
{
public function category() {
return $this->hasOne('App\Category','id','category_id');
}
}
上面会告诉 Laravel,当你在 post
中请求 category
属性时,它应该从 post 表中获取 category_id
并寻找 id
在类别表中。如果两者都匹配,它将为您提供匹配的类别。
关于php - 没有外键的 Laravel 一对一关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42734284/