问题
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.
The method
Jenssegers\Mongodb\Model::embedsMany()
expects parameter 1 to be the fully qualified name of another model, just likehasMany
in Eloquent does. You should create a ModelComment
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); } }
In your view, the variable
$j
should then be an instance ofComment
. 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