关系不在Laravel和MongoDB中工作?

时间:2014-02-03 14:00:49

标签: php mongodb laravel-4

Hello iam正在使用LAravel和MOngodb App: 我有以下情景:     我有评论和他们的点击集合,如下所示: Hoots模型系列

 "_id": ObjectId("52ef89e9c6b93ca123f2fd37"),
 "user_id": "52df9ab5c6b93c8e2a8b4567",
 "hoot": "Hello Thius is Tewst",
 "updated_at": ISODate("2014-02-03T12:22:01.530Z"),
 "created_at": ISODate("2014-02-03T12:22:01.530Z") 

和它的点击模型收集如下:

 "_id": ObjectId("52ef8d5ec6b93c6d24f2fd37"),
 "created_at": ISODate("2014-02-03T12:36:46.130Z"),
 "dip": NumberInt(1),
 "hits": NumberInt(0),
 "post_id": "52ef89e9c6b93ca123f2fd37",
 "updated_at": ISODate("2014-02-03T13:35:20.766Z") 

所以这里有一条评论,即hoot有一个描述他们喜欢和不喜欢的集合

我有一个模特anem Hoots

<?php

 use Jenssegers\Mongodb\Model as Eloquent;

 class Hoots extends Eloquent {

/**
 * The database table used by the model.
 *
 * @var string
 */
 protected $table = 'hoots';

 public $timestamps = true;

 protected $fillable = array('user_id', 'hoot');

  public function gethit()
 {
   return $this->hasOne('Hitdip');
 }
 }

和Hitdip模型的命中记录

<?php
use Jenssegers\Mongodb\Model as Eloquent;

class Hitdip extends Eloquent {

/**
 * The database table used by the model.
 *
 * @var string
 */
 protected $table = 'hitdip';

 public $timestamps = true;

 protected $fillable = array('post_id','hits', 'dip' ,'type');

  public function gethoot()
 {
   return $this->BelongsTo('Hoots');
 }

}

但是当我试图获取hoot并点击与他们相关的记录时,我收到了错误

 Hoots::where('user_id',$user_id)->gethit;

请审核? 错误

Undefined property: Jenssegers\Mongodb\Eloquent\Builder::$gethit (View: /var/www/hututoo/app/views/profile/profile_connect/profile.blade.php) (View: /var/www/hututoo/app/views/profile/profile_connect/profile.blade.php)

2 个答案:

答案 0 :(得分:2)

在一对一的关系中,事情很简单。以上关系定义正确。但我们需要以这种格式获取内容

Hoots::with('gethit')->find(id)->get();
Hoots::with('gethit')->where('user_id',$user_id)->get();

答案 1 :(得分:0)

有些时候,类名不会被视为对象,所以你必须直接传递给函数。

您需要更改gethit和gethoot函数,并且需要传递类对象 例如:

public function gethit(){
   return $this->hasOne(new gethit(),'Hoots','post_id','_id');
}

与gethoot相同

public function gethoot(){
  return $this->BelongsTo(new Hoots()); 
}

在像Hoots这样的一对多关系中有很多帖子。所以你可以打电话给

$posts = Hoots::with('gethit')->where('user_id','52df9ab5c6b93c8e2a8b4567')->get();