2016-10-18 33 views
1

我正在檢索分配給用戶的所有故障單。單個票據具有用戶表的外鍵。這是下面的代碼:如何根據Laravel中的刀片和控制器中的ID獲取列值?

App\Models\User.php 
protected $appends = ['full_name', 'avatar']; 

public function getFullNameAttribute() 
{ 
    return $this->first_name . ' ' . $this->last_name; 
} 


App\Http\Controllers\TicketsController.php 
/** 
* Display a listing of the resource. 
*/ 
public function index() 
{ 
    $tickets = Ticket::paginate(25); 

    $users = User::all(); 

    //return view('user.tickets.index', compact('tickets')); 
    return View::make('user.tickets.index', compact('tickets','users')); 
} 

Resources/Views/User/Tickets/index.blade.php 

      <table class="table table-striped table-bordered"> 
      <thead> 
       <tr> 
        <th>Status</th> 
        <th>Assigned To</th> 
       </tr> 
      </thead> 
      <tbody> 

      @foreach($tickets as $item) 
       <tr> 
        <td>{{ $item->status }}</td> 
        <td>{{ $item->user_id }}</td> 
       </tr> 
      @endforeach 


      </tbody> 

     </table> 

我要到外地{{$用品 - > USER_ID}}轉換爲{{$用品 - > FIRST_NAME其中id = $用品 - > USER_ID}}領域應該轉換成名字根據$ item-> user_id

user_id是門票的外鍵,相當於它是Users表的。

請幫忙。

回答

2

首先,它不是寫在意見DB查詢很好的做法。您可以通過在您的Ticket模型類中定義一個關係來完成該任務。

public function user() 
{ 
    return $this->belongsTo(User::class); 
} 

現在您可以通過$item->user->first_name訪問用戶名。

+0

謝謝你讓我知道。我只知道在視圖中編寫數據庫查詢並不是一個好習慣。你是一個天才。你的回答是正確的 –

2

試試這個:

@foreach (DB::table('table_name')->where('id', '=', $tickets->id)->get() as $id) 
      {{ $id->id }} 
      {{ $item->column_val1}} 
      {{ $item->column_val2}} 
      {{ $item->column_val3}} 
@endforeach 
+0

OP爲什麼要「試試這個」?一個好的答案***將總是解釋所做的事情以及爲什麼這樣做,不僅是爲了OP,還是爲了將來訪問SO。 –

相關問題