基本的に、私はユーザー、投稿、返信データベースの間にリレーションシップを作成しようとしています。ここでのモデルは以下のとおりです。 コメントモデルlaravel eloquent relationshipsエラー
<?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');
}
}
メインコード:
私はコメントページをaccesingてる<?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);
}
}
、私は取得しています、次のエラー:未定義のプロパティ:\ Database \ Eloquent \ Relations \ BelongsTo :: $ nameを照合します。 私は初めて関係を使用しているので、laravelドキュメントをチェックしましたが、私が間違っていたことはまだ分かりません。基本的に私が得ようとしているのは、ユーザのデータベースからユーザの名前を取得すること(コメントuser_idを外国語として使用)、コメントの詳細(本文、評価)を取得し、post_id(返信表)を外国とコメントの表ローカルキーとしてのプライマリキーID。