我正在尝试通过slug列从表注释中的列到故事表中获取数据。我已经成功地与作者合作,但我认为我必须遗漏某些东西或忘记某些东西,因为它不再有效。我收到此错误
Collection.php第1498行中的异常:此集合实例上不存在属性[comment]。
我的控制器功能
public function slug($slug){
$menus_child = Menu::where('menu_id', 0)->with('menusP')->get();
$stories = Story::where('slug', $slug)->get();
$slug = $slug;
// I used this to get the author's email going through the slug from
// story table
$story = Story::with('author')->where('slug', $slug)->first();
$name = $story->author->first()->email;
// I would like to get the name in the comment table by going through
// the slug from the story table
$comment = Story::with('comment')->where('slug', $slug)->get();
$test = $comment->comment->first()->name;
return view('open::public.single-story', compact('menus_child', 'stories', 'slug'));
}
my Comment.php
namespace App\Modules\Authors\Models;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
protected $fillable = array('name', 'comment');
protected $guarded = array('id');
protected $table = 'comments';
//Validation rules
public static $rules = array(
'name' => '',
'comment' => ''
);
public function story(){
return $this->belongsToMany('App\Modules\Authors\Models\Story', 'comment_story', 'comment_id', 'story_id');
}
}
my Story.php
class Story extends Model
{
protected $fillable = array('title', 'content', 'type', 'slug');
protected $guarded = array('id');
protected $table = 'story';
//Validation rules
public static $rules = array(
'title' => '',
'content' => '',
'type' => ''
);
public function slug($title){
$this->attributes['title'] = $title;
$this->attributes['slug'] = Str::slug($title);
}
public function author(){
return $this->belongsToMany('App\Modules\Authors\Models\Author', 'author_story', 'story_id', 'author_id');
}
public function comment(){
return $this->belongsToMany('App\Modules\Authors\Models\Comment', 'comment_story', 'story_id', 'comment_id');
}
}
答案 0 :(得分:3)
在dparoli的帮助下,我成功了。我想不起这么久才能把它弄清楚。
我改变了
$comment = Story::with('comment')->where('slug', $slug)->get();
$test = $comment->comment->first()->name;
到
$comment = Story::with('comment')->where('slug', $slug)->first();
$test = $comment->comment->toArray();
我将测试添加到
return view('open::public.single-story', compact('menus_child', 'stories', 'slug', 'test'));
然后添加
@foreach($test as $t)
<h1>{!! $t['name'] !!}</h1>
<p>{!! $t['comment'] !!}
@endforeach
到我的观点
答案 1 :(得分:0)
尝试改变这一点:
//here you get a collection of stories
$comment = Story::with('comment')->where('slug', $slug)->get();
对此:
//here you get a single story
$comment = Story::with('comment')->where('slug', $slug)->first();
答案 2 :(得分:0)
我给你一个不同的尝试方法
$comments = Comment::with(['story' => function ($query) {
$query->where('slug', '=', $slug);
}])->get();
如果它适用于你想要完成的任务,那就试一试。