繁体   English   中英

Laravel与多个模型的关系

[英]Laravel relations with multiple models

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

PostCityNeighbourhoodSubNeighbourhood

我到现在为止的关系是CityNeighbourhoodsubNeighbourhood Neighbourhood之间的关系如下:

subNeighbourhood belongs to Neighbourhood 
Neighbourhood belongs to city

第二种关系就像

City hasMany Neighbourhoods 
Neighbourhood hasMany subNeighbourhoods 

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

我的问题是:

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

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

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

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

因此,帖子属于属于属于城市的社区的Subneighbourhood

我认为多态关系将是解决问题的一个很好的解决方案。 (我没有测试我的代码或者有什么问题)

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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM