2017-12-03 173 views
1

我想在過去24小時內顯示10個存入和取出金額的人。我能夠在那裏顯示user_id和金額,但我想用戶名而不是user_id。如何從Laravel的用戶標識中獲取用戶名?

它正在爲基金不退出

我在$資金沒有名字科拉姆和$ withdrae它是在用戶我有這樣的代碼:

<div class="col-md-6"> 
<div class="text-center"><h4 class="text-success">Last 10 Investors</h4></div> 
<table class="table text-white" > 
    <tbody> 
     @foreach(\App\Fund::where('created_at', '>', \Carbon\Carbon::now()->subHours(24))->orderBy('id', 'DESC')->take(10)->get() as $fund) 
     <tr> 
      <th scope="row"></th> 
      <td>{{ $fund->user_id }}</td> 
      <td class="text-center text-warning">{{ $fund->total }}</td> 
      <td class="text-right"><img src="https://adsok.com/img/btc.png" alt="Bitcoin"> <i><b>bitcoin</b></i><br></td><br> 
     </tr>@endforeach 

    </tbody> 
</table> 

對於退出

<div class="col-md-6"> 
<div class="text-center"><h4 class="text-success">Last 10 Investors</h4></div> 
<table class="table text-white" > 
    <tbody> 
     @foreach(\App\Withdraw::where('created_at', '>', \Carbon\Carbon::now()->subHours(24))->orderBy('id', 'DESC')->take(10)->get() as $withdraw) 
     <tr> 
      <th scope="row"></th> 
      <td>{{ $withdraw->user_id }}</td> 
      <td class="text-center text-warning">{{ $withdraw->total }}</td> 
      <td class="text-right"><img src="https://adsok.com/img/btc.png" alt="Bitcoin"> <i><b>bitcoin</b></i><br></td><br> 
     </tr>@endforeach 

    </tbody> 
</table> 

我已經在這兩個基金粘貼同樣的關係,並退出模型

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

如果你已經設置了用戶關係,你可以用'$ fund-> user-> id'或'$ fund-> user-> name'來調用用戶數據。如[此處]所述(https://laravel.com/docs/5.5/eloquent-relationships#one-to-many-inverse)。 – vozaldi

回答

0

添加with('user')到查詢:

Fund::with('user')->where('created_at', '>', Carbon::now()->subHours(24))->orderBy('id', 'desc')->take(10)->get() 

然後你就可以顯示用戶名:

{{ $fund->user->name }} 

另外,do not run any queries in Blade templates,這是一個不好的做法。

+0

爲什麼我的代碼無法正常工作。也有關係 –

+0

@WaqarAli什麼是不工作?你有什麼錯誤嗎?如果沒有,請添加'{{dd(\ App \ Fund :: with('user') - > where('created_at','>',\ Carbon \ Carbon :: now() - > subHours( 24)) - > orderBy('id','DESC') - > take(10) - > get())}}'回答您的問題。 –

+0

這是說試圖獲得非物件的財產 –

0

您的WithdrawFund模型應該與User模型有belongsTo關係。

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

然後,每當您嘗試訪問相關的Fund一個User,你可以簡單地做

$fund->user->name 

但可以有機會在那裏Fund沒有任何相關User,所以你需要檢查在訪問它的屬性之前它是存在的。

$fund->user ? $fund->user->name : "na" 

但是你當你訪問的模式集合中的關係,每次會執行另一個查詢要小心。爲了防止這種情況,您可以使用with這樣的方法急切加載關係。

$funds = Fund::with('user')->get(); 
foreach($funds as $fund) { 
    echo $fund->user ? $fund->user->name : "na"; 
} 
相關問題