简体   繁体   中英

Relations not working in Laravel and MongoDB?

Hello iam working LAravel and MOngodb App: I have Following Scenario: I have Comment and their hits collection like this: Hoots Model Collection

 "_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") 

and Its hits Model collecton like this:

 "_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") 

So here One comment ie hoot have one collection describing their like and dislikes

i have a model 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');
 }
 }

And Hitdip model for their hits record

<?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');
 }

}

But When i am trying to get hoot and hit record related to them , i am getting an error

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

Kindly review? Error

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)

In one- to one relationship things are simple. above relations are defined correctly. But we need to fetch things in this format

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

Some time Class name does not treat as object so you will have to pass directly in the function.

You need to changed the gethit and gethoot function and you need to pass class object example:

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

Same as for gethoot

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

In one- to many relationship like Hoots have many post. So you can call

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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