Laravel,更好的链接到图像的方式

时间:2016-12-01 20:59:01

标签: php laravel

我有以下代码,它通过id获取图像:

    //concertscontroller

    foreach($concerts as $concert){
        $concert->image = Image::find($concert->image_id);
    }

从这个模型中获取

namespace App;
use Illuminate\Database\Eloquent\Model;

/**
 * @property string path
 * @property string name
 * @property string alt
 * @property string caption
 * @property int width
 * @property int height
 */
class Image extends Model
{
    //
}

-

/**
 * @property string name
 * @property string address_1
 * @property string address_2
 * @property string address_3
 * @property float(10,6) coordinates
 * @property string copy
 * @property int imageId
 * @property string ticket_link
 * @property string info_link
 * @property DateTime datetime
 */

class Concerts extends Model
{
    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function image()
    {
        return $this->hasOne('App\Image','id','imageId');
        //I don't think this does anything
    }
}

我不记得就像我不久前写的那样,但我认为hasOne关系应该允许我使用一些Laravel外观来自动获取图像。有谁知道如何做到这一点?如果我正确行事,请告诉我!

1 个答案:

答案 0 :(得分:1)

    foreach($concerts as $concert){
        $concert->image = Image::find($concert->image_id);
    }

-

 namespace App;
    use Illuminate\Database\Eloquent\Model;

    class Image extends Model
    {
           public function concerts()
        {
            return $this->belongsTo('App\Concerts');
        }
    }

-

 class Concerts extends Model
    {
        /**
         * @return \Illuminate\Database\Eloquent\Relations\HasOne
         */
        public function image()
        {
            return $this->hasOne('App\Image','id','imageId');
            //I don't think this does anything
        }
    }

在添加belongsTo关系后,这应该是技巧。