我正在尝试在 Laravel 4 中建立多态关系,这样我就可以拥有一个 Image 类来处理与上传、取消链接等相关的所有事情,然后让多个不同的模型使用它。没关系,直到我开始尝试从同一模型创建多个链接。
例如,我目前有这样的东西:
模型/Image.php
class Image extends Eloquent {
public function of() { return $this->morphTo(); }
}
模型/Person.php
class Person extends Eloquent {
public function mugshot() { return $this->morphOne('Image', 'of'); }
public function photos() { return $this->morphMany('Image', 'of'); }
}
模型/Place.php
class Place extends Eloquent {
public function photos() { return $this->morphMany('Image', 'of'); }
}
在这里,一个人可以上传一张面部照片
和许多照片
,而一个地方可以有很多照片
。问题是,当我为一个人创建一张 面部照片
时,它会将其保存到数据库的 images
表中:
id: 1
of_id: 1
of_type: Person
它不存储它是一张面部照片
而不是照片
的事实,所以当我去检索它时,$person->mugshot
有时可能会返回 $person->photos
之一,反之亦然。
是否有 (a) 比在同一模型上创建 2 个链接更好的方法,或者 (b) 实际使这种方法起作用的方法?
最佳答案
目前没有内置方式。也许在 Laravel 4.1 中应该会带来对多态关系的完全重写。
为Image
添加一个type
属性,然后在关系上定义where
条件:
public function mugshot() {
return $this->morphOne('Image', 'of')->where('type', 'mugshot');
}
public function photos() {
return $this->morphMany('Image', 'of')->where('type', 'photo');
}
不要忘记在您创建的Image
上设置type
。
或者,就像我在下面所做的那样,将该逻辑隐藏在模型中。
这是我的代码(我使用的是带有短数组表示法的 PHP 5.4):
图片:
namespace SP\Models;
class Image extends BaseModel {
const MUGSHOT = 'mugshot';
const PHOTO = 'photo';
protected $hidden = ['type'];
public function of()
{
return $this->morphTo();
}
}
人:
namespace SP\Models;
use SP\Models\Image;
class Person extends BaseModel {
public function mugshot() {
return $this->morphOne('SP\Models\Image', 'of')
->where('type', Image::MUGSHOT);
}
public function photos() {
return $this->morphMany('SP\Models\Image', 'of')
->where('type', Image::PHOTO);
}
public function saveMugshot($image)
{
$image->type = Image::MUGSHOT;
$image->save();
$this->mugshot()->save($image);
}
public function savePhotos($images)
{
if(!is_array($images))
{
$images = [$images];
}
foreach($images as $image)
{
$image->type = Image::PHOTO;
$image->save();
$this->photos()->save($image);
}
}
}
Controller /服务中的某处:
$person->savePhotos([$image1, $image2]);
关于php - Laravel 4,一个模型的多个多态关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19835996/