我创建了一个files
表来存储文件的元数据以及查找该文件的本地路径。
我想用这张桌子,用于多种型号。
例如,users
可以在此表中存储配置文件图片。但是companies
可以将他们的徽标存储在这个表中。所以实际上,我所有可以存储文件的模型都与这个表有关系。
因此,在users
和companies
中,我创建了一个列file_id
,它引用了files
表上的id
。因为files
表可以存储多个模型的文件,所以我不会在“files表”中存储user_id
或company_id
。
现在的问题是,如何将这种关系添加到users
和companies
表中?因为据我所见,它要求files
表具有users
或companies
的id。
我遗漏了什么?
发布于 2018-11-08 07:00:22
这看起来像一个多态关系。从文件中:
多态关系 表结构 多态关系允许一个模型在单个关联上属于多个其他模型。例如,想象一下您的应用程序的用户可以在帖子和视频上“评论”。使用多态关系,您可以为这两种情况使用一个
comments
表。首先,让我们检查构建这种关系所需的表结构: 张贴id -整数标题-字符串正文-文本视频id -整型标题-字符串url -字符串注释id -整数体-文本commentable_id -整数commentable_type -字符串 需要注意的两个重要列是commentable_id
表中的comments
列和comments
表上的commentable_type
列。commentable_id
列将包含post或视频的ID值,而commentable_type
列将包含所属模型的类名。commentable_type
列是ORM在访问commentable
关系时如何确定要返回的拥有模型的“类型”。 模型结构 接下来,让我们研究构建这种关系所需的模型定义: 使用照明\数据库\雄辩\模型;类注释扩展模型{ /** *获取所有拥有的可评论模型。*/ public函数式评论员(){传回$this->morphTo();} class Post扩展Model { /** *获取该帖子的所有注释。*/公共函数注释(){返回$this->变形Model (‘App\注释’,‘评论性’);}类视频扩展模型{ /** *获取所有视频评论。*/公共函数注释(){返回$this->变形this(‘App\注释’,‘评论性’);}
因此,在您的示例中,您的文件表结构可能如下所示:
files
id - integer
url - string
fileable_id - integer // <--- the id of the object
fileable_type - string // <-- the type of the object (user, company, etc)
那么在你们的模特中:
File.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class File extends Model
{
/**
* Get all of the owning fileable models.
*/
public function fileable()
{
return $this->morphTo();
}
}
User.php
class User extends Model
{
/**
* Get all of the user's files.
*/
public function files()
{
return $this->morphMany(File::class, 'fileable');
// or
// return $this->morphOne(File::class, 'fileable'); equivalent to hasOne
}
}
Company.php
class Company extends Model
{
/**
* Get all of the company's files.
*/
public function files()
{
return $this->morphMany(File::class, 'fileable');
// or
// return $this->morphOne(File::class, 'fileable'); equivalent to hasOne
}
}
发布于 2018-11-08 07:24:23
你走的方向是对的。
您可以在您的users
表中使用companies
和files
外键。
在Laravel 5多态关系中。
https://laravel.com/docs/5.7/eloquent-relationships#polymorphic-relations
您可以拥有外键fileable_id
和外键fileable_type
的类型。
如果要为companies
记录添加一个文件
假设您的公司id为24,您正在使用的模型是App\Models\Company
将以下内容添加到文件模型App\File
中
public function fileableable()
{
return $this->morphTo();
}
然后跟着你的App\User
和App\Company
public function files()
{
return $this->morphMany('App\Comment', 'fileable'); // use morphOne if you want One to One relation
}
若要为公司创建文件,请执行以下操作。
$company = Company::find(24);
$company->files()->create([
'path' => '/folder/myfile.txt',
'size' => '14585',
'extension' => 'txt',
]);
在这个阶段,您可能会得到MassAssignmentException
在您的App\File
模型中
添加$fillable = ['path', 'size' , 'extension'];
你的记录看起来如下:
id path size extension fileable_id fileable_type
1 /folder/myfile.txt 14585 txt 24 App\Models\Company
Laravel通过调用关系方法的对象自动存储fileable_id
和fileable_type
。你不用手动把这些
提示:总是要通过官方文档
https://stackoverflow.com/questions/53210266
复制相似问题