2017-01-02 7 views
0

В принципе, я пытаюсь создать связь между пользователем, сообщением и ответом db. Вот модели: комментарий моделиlaravel eloquent relationship error

<?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); 
    } 
} 

когда я экранная страницу комментариев, я получаю следующее error: Неопределенное свойство: Illuminate \ Database \ Eloquent \ Relations \ BelongsTo :: $ name. Это мой первый опыт использования отношений, поэтому я проверил документы laravel, но до сих пор не знаю, что я сделал неправильно. В основном то, что я пытаюсь получить, - это получить имя пользователя из базы данных пользователей (используя комментарии user_id как иностранные), получить информацию о комментариях (тело, рейтинг) и получить данные ответа, используя post_id (в таблице ответов) как чужой и таблицы комментариев Идентификатор первичного ключа как локальный ключ.

ответ

0

Вы получаете определение отношения от своих моделей вместо связанных объектов.

Заменить

$user = comments::find($comment->user_id)->userInfo(); 
$reply = comments::find($comment->id)->reply(); 
$user_reply = reply::find($comment->id)->user(); 

с

$user = comments::find($comment->user_id)->userInfo; 
$reply = comments::find($comment->id)->reply; 
$user_reply = reply::find($comment->id)->user; 

Примечание снятые скобки в самом конце этих линий.

0

меня внесены изменения, касающиеся некоторых отношений в цикле Еогеасп, которые сделают его более быстрым и более удобным

You are using relationship and still finding user using array key it's more likely to use on $comment bcz $comment is already Model and you can apply relationship on that easily. as same as for replay Model.

foreach ($comments as $comment) 
    { 
     $user = $comment->userInfo(); 
     $reply = $comment->reply(); 

     $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'] = $re->user()->name; 
       $replyData[$re->post_id][$re->id]['body'] = $re->body; 
      } 
     } 
Смежные вопросы