如何将存储在其他表中的图像的id存储在Laravel的users表中

时间:2018-01-26 20:46:40

标签: database laravel

我正在使用Laravel 5.5,我希望我的用户在注册时上传个人资料图片,以便它的路径将存储在'images'表中,其中包含image_id,image_path和我希望{的值{1}}同时存储在image id表中。

任何人都可以帮我做。

1 个答案:

答案 0 :(得分:1)

回答原始问题:

$user->images()->save($image);

快捷方式:users

associating的文档。

请求教程:

所以我们有一个简单的Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->string('password')->nullable(); $table->rememberToken(); $table->timestamps(); }); 表:

user_images

我们有一个simlpe Schema::create('user_images', function (Blueprint $table) { $table->increments('id'); $table->unsignedInteger('user_id')->nullable(); // user id $table->string('file')->unique(); // File path $table->boolean('is_index')->default(false); // is it profile picture? you can call this whatever you want $table->softDeletes(); // 'deleted_at' column for archive $table->timestamps(); }); 表:

User

<?php namespace App; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { use Notifiable, SoftDeletes; /** * 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', ]; /** * The attributes that should be mutated to dates. * * @var array */ protected $dates = [ 'deleted_at', ]; /** * Get the images for the user. * * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function images() { return $this->hasMany(UserImage::class); } } 型号:

UserImage

<?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class UserImage extends Model { use SoftDeletes; /** * All of the relationships to be touched. * * @var array */ protected $touches = ['user']; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'user_id', 'file', 'is_index' ]; /** * The attributes that should be mutated to dates. * * @var array */ protected $dates = [ 'deleted_at' ]; /** * Get the user that owns the image. * * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function user() { return $this->belongsTo(User::class); } } 模型:

User::find(1)->images;

这就是用户拥有多张图片的方式。

如果要在控制器中检索用户所有图像:

$user = User::find(1);
foreach($user->images as $images) {
    echo $user->file;
}

例如:

UserImage

您可以为public function scopeAvatar($query) { $query->where('is_index', '=', '1')->first(); } // Usage: $user->image->avatar->file // Only the profile picture 模型添加范围,以便更轻松地获取个人资料照片

{{1}}

之证件: