2017-07-28 38 views
0

我在我的數據庫中的這些關係laravel口才不行

Schema::create('my_users', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->timestamps(); 
     $table->string('fullName'); 
     $table->string('userName'); 
     $table->string('password'); 
     $table->string('photo'); 
     $table->string('email'); 
    }); 

Schema::create('posts', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->timestamps(); 
     $table->string('photo'); 
     $table->text('caption'); 
     $table->integer('like'); 
     $table->integer('my_user_id'); 
    }); 

我的模型:

class myUser extends Model 
{ 
    public function post() 
    { 
     return $this->hasMany('App\post'); 
    }   

} 
class post extends Model 
    { 
     public function user() 
     { 
      return $this->belongsTo('App\myUser'); 
     } 


} 

現在我試圖讓使用以下代碼的用戶數據:

$post = post::find(1);   
$user = $post->user; 

但它不起作用,$ user爲NULL。 我敢肯定,在職位表中有ID爲1 記錄怪異的一部分是這樣的,我沒有錯誤,當我改變方法的名字是這樣的:

$post = post::find(1);   
$user = $post->somethingBullshit; 

我使用laravel 5.3 。

請幫忙。

+0

我不知道,但我想我已經有這個問題。我想這是因爲你的「職位」班的名字。嘗試重新命名模型和表格中的「myPost」,看看它是否有效。 – tompec

回答

0

確認你命名你的類文件開頭大寫字母,並相應地修改您的類聲明,如:

class MyUser extends Model 
{ 
    public function post() 
    { 
     return $this->hasMany('App\Post'); 
    }   
} 

class Post extends Model 
{ 
    public function user() 
    { 
     return $this->belongsTo('App\MyUser'); 
    } 
} 

然後你可以選擇用戶,當你利用eloquent'swith(),以獲取信息方法,並從$post變量獲得您$user變量,或者只是使用後的用戶屬性如下:

$post = Post::with('user')->find(1); 
$user = $post->user; 
+0

我也確定存在相關的用戶記錄。 – blank94

+0

如果您返回$ post它是否包含您期望的信息或者它是否爲空/ NULL? – commanderZiltoid

+0

沒有$ post與預期數據一致。 – blank94