【问题标题】:Fetch data in single Eloquent Query laravel using relations?使用关系在单个 Eloquent Query laravel 中获取数据?
【发布时间】:2014-03-12 09:02:34
【问题描述】:

我正在开发社交应用前端 Angualar、后端 laravel 和数据库 Mongodb。我有这样的模型:

Hoots
-----------------
 - _id
 - content
 - publish_id

Article 
-----------------
 - _id
 - content
 - publish_id

Story
-----------------
 - _id
 - content
 - publish_id

Publish
-----------------
 - _id
 - post_id
 - type
 - user_id

publish 中的 Post id 属于 hoots 、 article 和 story 中的 _id ,其中 type 表示它是 hoot 、 article 还是 story。

我有这样的模型

//Article model 
class Article extends Eloquent {

  public function getpublish(){
     return $this->hasMany('Publish','post_id');
    }
  }
 //Story model 
 class Story extends Eloquent {

  public function get_publish(){
     return $this->hasMany('Publish','post_id');
    }
  }

 //Hoots model 
 class Hoots extends Eloquent {

  public function get_publ(){
     return $this->hasMany('Publish','post_id');
    }
  }

//Publish model 
 class Publish extends Eloquent {

  public function getdata(){

     return $this->BelongsTo('Hoots','Article','Story','publish_id');
    }
  }

我正在使用

  Publish::with('getdata')->where('user_id',Auth::user()->id)->get(); 

使用这个我只能在一个模型中获取发布数据以及 post_id 对应的数据,即仅 hoots。我想从所有三个表中得到这个。

我想获取发布模型数据及其对应的 post_id 数据。如何使用 eloquent 完成这个单一查询。

【问题讨论】:

  • 很难弄清楚你的要求。你能提供一张你期望的结果表吗?\
  • @Gaz_Edge 我已经更新了代码。请查看。如何从具有外键 publish_id 的三个不同模型中获取发布模型数据以及 post_id 对应数据?

标签: mongodb laravel-4 eloquent


【解决方案1】:

我想你的人际关系可能没有正确设置;

//Publish model 
 class Publish extends Eloquent {

  public function hoot(){

     return $this->HasMany('Hoots','publish_id');
    }
  }

  public function article(){

     return $this->HasMany('article','publish_id');
    }
  }

  public function story(){

     return $this->HasMany('stort','publish_id');
    }
  }

Publish::with(array('hoot', 'story', 'article'))->where('user_id',Auth::user()->id)->get(); 

【讨论】:

  • 我不知道为什么,但这个东西不起作用,我只是得到 Id 而不是内容?如上图所示,我在连接中指定表名。我使用的数据库是 mongodb
  • 很棒的人。我正在尝试同样的事情,但与属于。 hasmany 有魅力。谢谢
猜你喜欢
  • 2020-11-07
  • 2017-10-18
  • 1970-01-01
  • 2017-07-07
  • 1970-01-01
  • 2014-10-29
  • 2017-05-01
  • 2021-12-10
  • 2022-01-03
相关资源
最近更新 更多