2015-06-24 63 views
0

我是Laravel5的新手,即使我已經在我的網站上取得了一些進展,但我陷入了對您而言可能很簡單的事情中。 我有2個表:用戶和書籍在laravel中加入2個表格

用戶:

UserID|FirstName|LastName 
1|John|Doe 
2|Mark|Lehman 
3|Dan|Edward 

書籍:(這意味着與用戶ID的ID的用戶已經與的BookID

BookID|UserID 
1|1 
1|2 
的ID讀取的書籍

我想查找ID爲1的所有用戶的名字和姓氏(我將此ID傳遞給函數finduser($ id)) 在上例中,finduser(1)應該return: John Doe Mark Lehman

(我認爲在php中就像:select(FirstName,LastName)從用戶加入Books(Users.ID = Books.userID)。

我在helpers.php中創建了函數finduser($ id)而不是控制器。我將這個函數調用到視圖中。我也很感興趣,我怎麼稱呼這個功能的回報到視圖中,我如何回顯它們...

你能幫我嗎?

+0

你的問題有一些範圍蔓延在尾巴上。在另一個問題中解決'查看'。包括你嘗試過的代碼片段,在這種情況下至少包括finduser函數。還發布了什麼錯誤正在拋出。 –

回答

0

我無法解決「視圖」的問題在anothe rtopic,因爲我創造了finduser功能呼應的某種看法......這裏的東西我已經做了:

 function finduser($id){ 
return $users=DB::table(users) 
    ->select('users.FirstName',’users.LastName’) 
    ->join(Books, Books.UserID','=',user.ID') 
    ->where(Books.ID','=',$id) 
    ->get(); 
} 

的觀點:

@if(finduser(targetID)!=null) 
    $us=finduser(targetID); 
    @foreach($us as $u) 
     {{$u}} 
    @endforeach 
@endif 

結果: 美元=訪客($用品 - > ID); ......這是非常愚蠢的...... enter code here

0

創建關係http://laravel.com/docs/5.1/eloquent-relationships

在用戶模式

public function books() { 
    return $this->hasMany('App\Book'); 
} 

在你的書的模型

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

然後,當你想找到擁有這本書的用戶,只需撥打你的書:

$book = Book::find(1); // find the book with id 1 
$book->user // This gives you the user that owns that book. Try dd($book->user);