php - 在 Laravel MongoDB 中显示 EmbedsMany 数据

标签 php mongodb laravel

我有一个包含如下方案的数据库:

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

我想显示标题和主题。

我的模型:

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

我的 Controller :

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

我的观点:

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

数据注释。

subject not show.   

请帮我展示一下。

最佳答案

我看到那里有两个问题。

  1. Jenssegers\Mongodb\Model::embedsMany() 方法期望参数 1 是另一个模型的完全限定名称,就像 Eloquent 中的 hasMany做。 您应该创建一个模型 Comment 并将您的 Testo 模型调整为以下内容:

    <?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. 在您看来,变量$j 应该是Comment 的一个实例。您可以像这样访问评论的主题:

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

如需进一步阅读,请查看官方 jenssegers/laravel-mongodb 文档,Embeds Many Relations 部分:

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

关于php - 在 Laravel MongoDB 中显示 EmbedsMany 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32666114/

相关文章:

php - Laravel Eloquent : How to select not attached records in many to many relationship?

ruby - 你如何使 belongs_to 成为 mongo 映射器所必需的?

mysql - 如何禁止接受已接受的汽车报价 Laravel

javascript - Mongoose 填充的Where子句

从 Laravel 的belongsToMany 关系中选择自定义列

php - Laravel 搜索关键字查询

PHP make 如果更短

php - 单击函数,Window.location

javascript - AJAX 调用传递 <div> 而不是 <button>

javascript - 无法完成 GET 请求