基本上,我正在尝试创建用户,发布和回复数据库之间的关系 . 以下是模型:评论模型
<?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);
}
}
当我访问评论页面时,我收到以下错误:
未定义属性:Illuminate \ Database \ Eloquent \ Relations \ BelongsTo :: $ name .
这是我第一次使用关系,所以我检查了Laravel文档,但仍然不知道我做错了什么 . 基本上我想要的是从用户数据库获取用户名(使用注释user_id作为外来),获取注释详细信息(正文,评级)并获取回复数据,使用post_id(在回复表中)作为外来和注释表主键ID作为本地键 .
2 回答
您从模型中获取关系定义而不是相关对象 .
更换
同
请注意这些行末尾的删除括号 .
我已经对foreach循环中的某些关系进行了更改,这将使其更快,更实用