我有一个包含如下方案的数据库:
{
"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.
请帮我展示一下。
最佳答案
我看到那里有两个问题。
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); } }
在您看来,变量
$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/