php - Laravel - 多对多关系

标签 php mysql laravel eloquent

我有 2 个表,用户图片。这些表具有多对多关系,我创建了一个名为 user_pictures 的数据透视表。

用户表如下:

id
firstname
lastname

图片表如下:

id
filename
url 

user_pictures 表包含:

id
user_id
picture_id

当用户添加图片时,图片filenameurl被存储在pictures表中,在user_pictures中 表该图片的 picture_id 与该用户的 user_id 一起存储。

我如何检索与使用 Eloquent ORM 添加的用户相关的所有图片 filenameurl

最佳答案

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $table = 'users';
    // Define pictures with a pivot table link
    public function pictures() {
        return $this->belongsToMany('App\Models\UserPicture', 'user_pictures', 'picture_id', 'user_id');
    }
    //add methods
}

class UserPicture extends Model
{
    protected $table = 'user_pictures';
    public function picture() {
        return $this->hasOne('App\Models\Picture', 'id', 'picture_id');
    }

    public function user() {
        return $this->hasOne('App\Models\User', 'id', 'user_id');
    }
    //add methods
}

class Pictures extends Model
{
    protected $table = 'pictures';
    //add methods
}

如果你不想在表中添加时间戳,你必须添加这两个方法:

 public function setCreatedAt($value) {
        // to disable created_at
    }

    public function setUpdatedAt($value) {
        // to disable created_at
    }

要从用户那里获取图片,请执行以下操作:

$userPictures = UserPicture::where(array('user_id'=>1)->get();
foreach($userPictures as $userpicture) {
    $picture = $userpicture->picture();
}

关于php - Laravel - 多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32991941/

相关文章:

laravel - 生产模式编译报错 "is not a function"Vue Laravel Mix

php - 关于重复 key 更新我做错了什么

php - Wordpress get_posts() 不返回所有带有 post_type=attachment 的帖子

php - 比较并显示不匹配的数据

mysql - 我可以在 ruby​​ on Rails 中使用存储过程吗?

laravel 向我显示此错误 该路由不支持 POST 方法。支持的方法 : GET, HEAD、PUT、DELETE

php - 为什么我的调试数据未格式化?

php - mysqli_query 和 bind_param 之间性能差异 10 倍(PHP 7)

php - Mysql查询使用同一个表中的其他列值分组获得第二和第三最小值

php - 刚刚安装了 Lumen 并得到了 NotFoundHttpException