2016-12-01 13 views
1

にリンクする、より良い方法I有しIDにより画像を取得し、次のコード:Laravel画像

このモデル

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 
{ 
    // 
} 

からグラブ

//concertscontroller 

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

-

/** 
* @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ファサードを使ってイメージを取得できるようにするべきだと思います自動的に。誰もこれを行う方法を知っていますか?もし私がそれをやっているなら、それは私にもあまり教えてください!

+0

return $ this-> hasOne( 'App \ Image'); ' – GabMic

+0

'は、$ this-> hasOne( 'App \ Image'、 'id'、 'imageId');これはデータベースにも依存し、外部キーの設定も必要です。 – CUGreen

答えて

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の関係を追加した後。

+0

これは、1つの画像が他のいくつかのクラスに属することができる場合ですか? – userqwert

+0

このケースでは、関数内で定義した1つのクラスに属しています。もしあなたが他の関係を作ったら、belongsToManyと言うことができます。 – GabMic