2017-10-12 97 views
0

我試圖讓2和表之間的關係:關係在laravel空5.5

我的模型:

class Modele extends Model 
{ 
public function shoe() 
{ 
    return $this->hasMany('Shoe'); 
} 
} 

class Shoe extends Model 
{ 
    public function modele() 
    { 
    return $this->belongsTo(Modele::class, 'IdModele','id'); 
    } 
} 

我的Controler:

class shoeController extends Controller 
{ 
public function index() 
{ 

$shoesList= \App\Shoe::with('modele')->orderBy('idModele')->get(); 

return view('shoe.index',compact('shoesList')); 
} 
} 

When I dd($shoeList) , I have this:

#relations: array:1 [▼ 
    "modele" => null 
    ] 

和如果我嘗試像這樣使用刀片中的參數:

<p>{{$shoe->modele->idGender}}</p> 

IHAVE此錯誤:

ErrorException thrown with message "Trying to get property of non-object (View: C:\laragon\www\ipepsShoes2017\resources\views\shoe\index.blade.php)

我有做桌子之間的其他關係,在這個項目中使用相同的方法和they'r工作的罰款。

我不明白爲什麼它不起作用。

謝謝。

+0

我不確定,但是在做'hasMany'時,你必須寫下表名,我不知道這個表是否是shoe的'shoe'。你能告訴我們你的表格結構嗎? – matiaslauriti

+1

return $ this-> belongsTo(Modele :: class,'idModele','id');我認爲我必須是小字母nto capse – iCoders

+0

這裏是我的表架構:https://photos.app.goo.gl/aGj9ATqhd8qxsMt92對不起,我不能上傳照片.... Modele和其他表格上的關係完美的作品... –

回答

0

試試這個

class Modele extends Model 
{ 
public function shoe() 
{ 
    return $this->hasMany('App\Shoe'); 
} 
} 

class Shoe extends Model 
{ 
    public function modele() 
    { 
    return $this->belongsTo('App\Modele', 'IdModele','id'); 
    } 
} 
在你看來首先檢查

{{的print_r($蹄式> MODELE)}}如果你得到對象,然後調用PARAM你需要什麼

+0

Thx,但我已經試過... –

+0

當我使print_r($ shoe-> modele)它只打印1。對於正在工作的其他關係,它打印所有參數... –

+0

只需要確認,bcs @Hamel沒有給出關於他修復什麼或爲什麼它會幫助你的任何解釋,所以你可能會錯過它:@Fred,你的原創代碼使用'return $ this-> hasMany('Shoe');'這是不正確的。您需要指定模型,如'return $ this-> hasMany('\ App \ Shoe');',或'return $ this-> hasMany(Shoe :: class);'。你解決了嗎? –

0

嘗試寫一個國外爲的hasMany關係的關鍵MODELE型號:

class Modele extends Model 
{ 
    public function shoe() 
    { 
     return $this->hasMany('Shoe', 'IdModele'); 
    } 
} 

希望它可以幫助你:)