基本上,我试图创建用户,发布和回复数据库之间的关系。下面是型号: 评论模型laravel雄辩关系错误
<?php
namespace App\Eloquent;
use Illuminate\Database\Eloquent\Model;
class comments extends Model
{
public $timestamps = true;
protected $table = 'comments';
protected $guarded = ['id'];
public function userInfo()
{
return $this->belongsTo('App\Eloquent\User', 'user_id');
}
public function reply()
{
return $this->hasOne('App\Eloquent\reply', 'post_id');
}
}
应答方式:
<?php
namespace App\Eloquent;
use Illuminate\Database\Eloquent\Model;
class reply extends Model
{
public $timestamps = true;
protected $table = 'replies';
protected $guarded = ['id'];
function user()
{
return $this->belongsTo('App\Eloquent\User', 'user_id');
}
}
主要代码:
<?php
namespace App\Http\Controllers;
use App\Eloquent\comments;
use App\Eloquent\reply;
use Illuminate\Http\Request;
class CommentsController extends Controller
{
public function index()
{
$commentsData = [];
$replyData = [];
$comments = comments::all();
foreach ($comments as $comment)
{
if($comments !== null) {
$user = comments::find($comment->user_id)->userInfo();
$reply = comments::find($comment->id)->reply();
}
if(reply::all() !== null) {
$user_reply = reply::find($comment->id)->user();
}
$commentsData[$comment->id]['name'] = $user->name;
$commentsData[$comment->id]['message'] = $comment->body;
$commentsData[$comment->id]['rating'] = $comment->rating;
$commentsData[$comment->id]['timestamp'] = $comment->created_at;
foreach($reply as $re)
{
$replyData[$re->post_id][$re->id]['name'] = $user_reply->name;
$replyData[$re->post_id][$re->id]['body'] = $reply->body;
}
}
return view('comments')->with('comments', $commentsData)->with('reply', $replyData);
}
}
当我accesing评论页面,我发现了以下错误:未定义的属性:Illuminate \ Database \ Eloquent \ Relations \ BelongsTo :: $ name。 这是我第一次使用关系,所以我检查了laravel文档,但仍然不知道我做错了什么。基本上我试图得到的是从用户数据库(使用评论user_id作为外国)获得用户的名称,获取评论详细信息(正文,评级),并获得答复数据,使用post_id(在回复表)作为外国和评论表主键ID作为本地键。