检索 laravel 集合中的所有元素

Retrieve all elements on laravel collection

我刚开始使用 Laravel。我目前正在创建某种 "Instagram" 应用程序作为示例。所以我有 4 张桌子。用户、图片、评论和点赞。我已经使用 php artisan 命令 make:model 创建了 "Models" 并将一些数据包含到数据库中。问题是,在创建模型的关系之后。

use App\Image;

class Comment extends Model
{
    protected $table = 'comments';
    protected $primaryKey = 'CommentId';

    public function user()
    {
        return $this->belongsTo('App\User', 'UserId');
    }

    public function image()
    {
        return $this->belongsTo('App\Image', 'ImageId');
    }
}

并在图像模型上做同样的事情


class Image extends Model
{
    protected $table = 'images';
    protected $primaryKey = 'ImageId';

    public function comments() 
    {
        return $this->hasMany('App\Comment', 'CommentId');
    }

    public function likes()
    {
        return $this->hasMany('App\Like', 'LikeId');
    }

    public function user()
    {
        return $this->belongsTo('App\User', 'UserId');
    }

我无法获取一张图片的所有评论,执行后:


Route::get('/', function () {
    $images = Image::all();


    foreach ($images as $image) {
        echo "Uploaded By: ".$image->user->FirstName."<br>";
        echo "<strong>Comments</strong><br>";

        foreach ($image->comments as $comment) 
        {
            echo "Comment: ".$comment->Content;
        }
    }
    die();
    return view('welcome');
});

即使图片有超过 1 条评论,我也只能在每张图片上获取一个元素。

我认为问题出在你的评论关系上:

 public function comments() 
    {
        return $this->hasMany('App\Comment', 'CommentId');
    }

应该是:

 public function comments() 
    {
        return $this->hasMany('App\Comment', 'ImageId');
    }

hasMany关系中的第二个参数应该是关联数据库中两个table的外键。

更多详情见:

https://laravel.com/docs/7.x/eloquent-relationships#one-to-many