기본적으로 사용자, 게시 및 회신 DB 간의 관계를 만들려고합니다. 여기 모델은 다음과 같습니다 코멘트 모델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를 foreign로 사용), 주석 세부 사항 (body, rating)을 얻고 post_id (응답 테이블에서)를 foreign 및 comments 테이블로 사용하여 응답 데이터를 얻는 것입니다. 로컬 키로 기본 키 ID.