Laravel与多个模型的关系

时间:2017-02-10 11:03:04

标签: php laravel laravel-5 laravel-5.3

我正在构建一个博客应用程序,我有

PostCityNeighbourhoodSubNeighbourhood

我到目前为止的关系介于CityNeighbourhoodsubNeighbourhood之间,如下所示:

subNeighbourhood belongs to Neighbourhood 
Neighbourhood belongs to city

第二种关系就像

City hasMany Neighbourhoods 
Neighbourhood hasMany subNeighbourhoods 

我的问题是我创建帖子的时候。帖子表包含id_cityid_neighbourhoodid_subNeighbourhood

我的问题是:

如果帖子结构正确吗?我觉得有很多“id _...”不行。

第二个问题是如何在帖子中写下关系?所有列“id _...”都有每个对应表的外键。

2 个答案:

答案 0 :(得分:0)

对于我从你的解释中可以理解的内容,post表应该只有一个subneighbourhood_id字段,在Post类中关系应该是:

public function subneighbourhood()
{
    return $this->belongsTo('App\Subneighbourhood');

所以帖子属于Subneighbourhood,属于属于城市的邻居

答案 1 :(得分:0)

我认为多态关系将是解决问题的好方法。 (我没有测试我的代码,也没有测试过什么)

class Post extends Model
{
   // Can return a City or Neighbourhood or SubNeighbourhood
   public function related() {
      return $this->morphTo();
   }
}

class City extends Model 
{
   public function posts() {
      return $this->morphMany(App\Models\Post::class, 'related');
   }
} 


class Neighbourhood extends Model 
{
   public function posts() {
      return $this->morphMany(App\Models\Post::class, 'related');
   }
} 

如何使用:

示例,如果我们有一个与城市相关的帖子

$post = Post::find(1);
$true = ($post->related instanceof City);  // This will be true if post related to a city
$neightbourhoods = $post->related->neightbourhoods(); // All the neightbourhoods of the city

示例如果我们有一个与邻居相关的帖子

$post = Post::find(2);
$true = ($post->related instanceof Neighbourhood); // This will be true if post is related to a neighbourhood
//In this case we can do
$post->neighbourhood->subNeighbourhoods(); // All the sub neighbourhoods

您可以使用

轻松安全发布
$post = new Post();
$post->related = City::find(1); 
$post->save();

or 

$post = new Post();
$post->related = Neighbourhood::find(1);
$post->save();