首页 > 解决方案 > 检索 laravel 集合上的所有元素

问题描述

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

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 条评论,我也只能在每张图像上获得一个元素。

标签: laravelcollectionseloquentormlaravel-7

解决方案


我认为问题出在您的评论关系中:

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

它应该是:

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

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

更多细节在:

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


推荐阅读