laravel - 检索 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 条评论,我也只能在每张图像上获得一个元素。
解决方案
我认为问题出在您的评论关系中:
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
推荐阅读
- c# - 多线程:等待线程完成,以便我可以重试死锁
- sql-server - 我正在尝试使用带有光标的存储过程或函数来减少重复的 SQL“代码”,我正在寻找建议/帮助
- docker - 在 gitlab shell 执行程序中运行 docker 时权限被拒绝
- macos - webGL macOS 上的 firefox webm 有时 yuv 有时 rgb
- c# - 如何使用 azure 函数使用托管标识连接 Azure SQL DW
- javascript - 如何使用 cookie 使弹出窗口消失?
- excel - 如何根据工作表名称将工作簿拆分为单独的文件?
- themes - 通过 github 操作部署的 github 页面上的 Hugo 网站不适用于自定义主题
- javascript - 如何使用 jQuery 检测屏幕大小变化的对象样式?
- laravel - 在 null 上调用成员函数 get_cellmap()