Laravel有很多地方

fob*_*bus 28 orm laravel eloquent laravel-4

我有3张桌子,汽车,公寓和商店.每张桌子都有照片.照片存储在数据库中.我想只使用一张桌子拍照,我不想为每辆汽车,公寓和商店创建照片表.

照片表结构是这样的;

| id |           photo_url        | type  | destination_id |
------------------------------------------------------------
  1  |   http://example.com/1.jpg | Cars  |      1         |
  2  |   http://example.com/2.jpg | Flats |      1         |
  3  |   http://example.com/3.jpg | Flats |      2         |
  4  |   http://example.com/4.jpg | Shops |      1         |
  5  |   http://example.com/3.jpg | Shops |      2         |
Run Code Online (Sandbox Code Playgroud)

我需要在Shops,Flats和Cars模型类中定义hasMany与类型的关系.

这样做的正确方法是什么?

Log*_*ley 68

您可以将关系对象视为类似查询,因为您可以使用它们调用查询构建函数.下面的例子可以让你朝着正确的方向前进.

class Cars extends Eloquent
{
    function photos()
    {
        return $this->hasMany('Photo')->where('photos.type', '=', 'Cars');
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢,我需要调用 `Order::with('orderItems')->where('orderItems.type',1)->with('orderItems.orderItemOptions', 'orderItems.orderMenuItems')->first( )`,并且范围不会那样工作 (2认同)
  • 有没有办法为此传递论据?在where子句中使用参数? (2认同)
  • 如果需要向“with”添加条件,请执行 with((['Model' => function ($query) { $query->where('title', 'like', '%first%'); }]) ) (2认同)

Bog*_*dan 15

你可以利用Eloquent的多态关系.Laravel文档中的示例实际上展示了为多个模型设置公共图像表,因此应该指向正确的方向.在您的情况下,您的模型看起来像这样:

class Photo extends Eloquent {

    public function imageable()
    {
        return $this->morphTo();
    }

}

class Car extends Eloquent {

    public function photos()
    {
        return $this->morphMany('Photo', 'imageable');
    }

}

class Flat extends Eloquent {

    public function photos()
    {
        return $this->morphMany('Photo', 'imageable');
    }

}

class Shop extends Eloquent {

    public function photos()
    {
        return $this->morphMany('Photo', 'imageable');
    }

}
Run Code Online (Sandbox Code Playgroud)

你可以访问照片,让我们说一个给定的Flat,像这样:

Flat::find($id)->photos;
Run Code Online (Sandbox Code Playgroud)

为此,您还需要在photos表中添加2个附加列:

imageable_id: integer  <-- This will be the ID of the model
imageable_type: string <-- This will be the model's class name (Car/Flat/Shop)
Run Code Online (Sandbox Code Playgroud)

  • Spasibo bratan! (4认同)