【问题标题】:Laravel relationships not working as expectedLaravel 关系没有按预期工作
【发布时间】:2017-12-13 21:11:21
【问题描述】:

所以我一直在构建这个简单的留言簿,人们离开 cmets。我已将用户模型链接到评论模型,并尝试返回发布评论的用户,但我总是收到错误消息。在此之前,我使用相同的代码制作了一个票务程序,它仍然可以正常工作。见下文

评论模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
  public function user()
  {
    return $this->belongsTo('User::class');
  }
}

用户模型

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function comments()
    {
      return $this->hasMany(Comment::class);
    }
}

这是我试图返回结果的控制器

<?php

namespace App\Http\Controllers;
use App\Comment;
use App\User;
use Auth;
use Illuminate\Http\Request;

class HomeController extends Controller
{

    public function index()
    {
      $comments = Comment::all();
      $user = Auth::user();
      $test = User::all();
      $average = number_format((Comment::avg('rating')),2, '.', '');
      dd($comments->user);
      return view('welcome')->withComments($comments)->withUser($user)->withAverage($average);

    }
}

每次我尝试 DD 时,我都会收到错误消息
此集合实例上不存在属性 [用户]。

我 100% 不明白为什么这将适用于一个项目而不适用于另一个项目。我什至重新构建了这个小应用程序,看看它是否是我所做的,我仍然得到相同的结果。

【问题讨论】:

  • return $this->belongsTo('User::class');应该返回 $this->belongsTo(User::class);或返回 $this->belongsTo('App\Models\User');
  • 还有 $cmets 它是一个对象的集合,因此您需要访问每个对象的用户。试试 $cmets->each(function($value){ dump($value->user->name; });
  • 如果你只想要当前用户的 cmets \Auth::user()->cmets;您应该在这里得到提示:Property [user] does not exist on this collection instance

标签: laravel debugging relationship


【解决方案1】:

您正在尝试get property of a collection,而不是对象。这样做:

foreach ($comments as $comment) {
    dump($comment->user); // $comment is an object
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-27
    • 1970-01-01
    • 1970-01-01
    • 2021-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多