2016-08-16 118 views
0

我試圖獲取與我的網站上給定用戶相關的配置文件。PHP Laravel雄辯的關係在使用findOrFail時不起作用

的關係是建立正確的(我可以這樣做:Auth::user() -> profile訪問配置文件數據,但是當我嘗試這樣做:User::findOrFail(1) -> profile它給了我一個錯誤說,它不是一個對象(和配置文件的值等於。null這是爲什麼是的與1的ID的用戶確實存在

在我User模型我設置這樣的:?

public function profile() { 
    return $this -> hasOne('App\Profile', 'user_id'); 
} 

在我Profile模型我已經做到了這一點:

public function user() { 
    return $this -> belongsTo('App\User', 'user_id'); 
} 

我剛剛看到這個問題,當抓住X用戶並在foreach循環中檢查它們時(如下所示)。

<div class="thumbs-wrapper text-center"> 

     @foreach ($last_online as $user) 
      <div class="thumb @if(\App\User::isOnline($user -> id)) online @else offline @endif"> 
       <a href="/profile/view/{{ $user -> id }}"> 
        <img src="{{ asset($user -> profile -> picture) }}"> 
       </a> 
      </div> 
     @endforeach 

    </div> 

什麼可能是錯的?提前致謝。

+0

一個或多個在用戶的foreach不具備個人資料,這就是全部 –

+0

所有用戶都有個人資料。它是在用戶註冊時創建的,具有與用戶相同的user_id。我也在我的數據庫管理器中手動檢查了這個。 – Kaizokupuffball

+0

然後檢查堆棧跟蹤並確定發生錯誤的位置。 –

回答

0

試試這個,如果我理解你的問題正確

User::with('profile')->where('id', '=', 1)->firstOrFail(); 

,或者如果你需要加載很多用戶與他們的個人資料

User::with('profile')->take(10)->get(); 
+0

這也不起作用。所有的用戶都有個人資料。它是在用戶註冊時創建的,具有與用戶相同的user_id。 這給了我這個錯誤:'調用undefined方法照亮\數據庫\查詢\生成器::配置文件()' – Kaizokupuffball

0
Call to undefined method Illuminate\Database\Query\Builder::profile() 

輪廓()存在於用戶模式?

嗯......它必須工作。

在用戶模式:

public function profile() { 
    return $this->hasOne('App\Profile', 'user_id'); 
} 

在你的控制器的方法:

$users = User::with('profile')->get(); 


dd($users); 

Illuminate\Database\Query\Builder::profile() Here's a screenshot also: i.imgur.com/zPJEaC5.png So weird I can use Auth::user() -> profile

:)

foreach ($users as $user) { 
$user->profile->user_id; //(or whathewer) 
}