2017-10-12 63 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'); 
    } 
} 

希望它可以帮助你:)