【发布时间】:2023-04-06 13:35:02
【问题描述】:
当我在 1 个视图中使用具有 3 个模型的 fooreach 循环时遇到问题
这是我的Thread 模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Thread extends Model
{
protected $primaryKey = "id_threads";
public function user(){
return $this->belongsTo('App\User','id_users');
}
protected $fillable = [
'id_users', 'threads',
];
public function comment(){
return $this->hasMany('App\Comment','id_threads');
}
}
这是我的Comment 模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
protected $primaryKey = 'id_comments';
public function thread(){
return $this->belongsTo('App\Thread','id_threads');
}
public function users(){
return $this->belongsTo('App\User');
}
protected $fillable = [
'id_threads', 'id_users', 'comments','status'
];
}
这是我的index 控制器
public function index()
{
$user = Auth::user();
$comment = Comment::all();
//Threads
$threads = Thread::orderBy('created_at','desc')
->get();
$hitung = $threads->where('id_users', '=',$user->id);
return view('/home',compact('threads','hitung','comment'));
}
这是我的view
@foreach ($threads as $thread)
<div class="media-body">
<h5 class="mb-0">{{$thread->user->name}}</h5>
<div class="card-date mb-2">
{{date('F d, Y', strtotime($thread->created_at))}} at {{date('g : ia', strtotime($thread->created_at))}}
</div>
<input type="hidden" name="$id_threads" value="{{$thread->id_threads}}">
{{$thread->threads}}
<div class="card-delete mt-5">
@if (Auth::user()->id==$thread->id_users)
<a href="">Delete</a>
@else
@endif
</div>
<hr>
<div class="media comment mt-3">
<a class="mr-3" href="#">
{{$thread->comment->comments}}
当我想显示评论时出现错误
{{$thread->comment->comments}}
然后出现这样的错误
Property [comments] does not exist on this collection instance. (View: D:\Jendro\Project Laravel\projectCO\resources\views\home.blade.php)
但是当我只调用对象时,像这样
{{$thread->comment}}
没有出现错误,在我看来,Comment 模型中出现了一个数据集
[{"id_comments":6,"id_threads":54,"id_users":2,"comments":"asdqweasd","created_at":"2020-06-29 08:58:53","updated_at":"2020-06-29 08:58:53","status":"comment"}]
调用用户对象的时候也是这样,但是调用用户对象的属性时用户对象没有问题
我被这个问题卡住了,有人有解决这个问题的方法吗?
【问题讨论】:
标签: php laravel laravel-5 eloquent