Display EmbedsMany Data in Laravel MongoDB

怎甘沉沦 提交于 2021-01-27 15:41:57

问题


I have a database with schemes like below:

{
    "title": "Simple new",
    "username": "soimah",
    "_id": ObjectId("5569b157bed33066220041ac"),
    "comments": [{
    "subject": "comment 1",
    "_id": ObjectId("5569cc28bed330693eb7acd9")
    }]
}

I would like to display the title and subject.

My Model:

<?php
namespace App\Models;
use Jenssegers\Mongodb\Model as Eloquent;

class Testo extends Eloquent {
    protected $collection = 'testIN';
    protected $fillable = array('title', 'comments.subject');

    public function comments() {
    return $this - > embedsMany('comments');
    }
}
?>

My Controller:

public function ambl() {
    $g = new Testo();
    $g = Testo::where('username', '=', 'soimah') - > first() - > comments;
    return View('layouts/in', array(
    'g' => $g
    ));
}

My View :

<?php
    foreach($g as $j) {
      echo $j['comments.subject'];
    }
?>

Data comments.

subject not show.   

Please help me to show them.


回答1:


I see two issues there.

  1. The method Jenssegers\Mongodb\Model::embedsMany() expects parameter 1 to be the fully qualified name of another model, just like hasMany in Eloquent does. You should create a Model Comment and adjust your Testo model to the following:

    <?php
    
    namespace App\Models;
    
    use Jenssegers\Mongodb\Model as Eloquent;
    
    class Testo extends Eloquent 
    {
        protected $collection = 'testIN';
    
        protected $fillable = array('title', 'comments.subject');
    
        public function comments()
        {
            return $this->embedsMany(Comment::class);
        }
    }
    
  2. In your view, the variable $j should then be an instance of Comment. You can access the subject of a comment like this:

    // Raw PHP view:
    <?php
    foreach ($g as $j) 
    {
        echo $j->subject;
    }
    ?>
    
    // Blade syntax:
    @foreach($g as $j)
        {{ $j->subject }}
    @endforeach
    

For further reading, please have a look at the offical jenssegers/laravel-mongodb documentation, section Embeds Many Relations:

https://github.com/jenssegers/laravel-mongodb#embedsmany-relations



来源:https://stackoverflow.com/questions/32666114/display-embedsmany-data-in-laravel-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!