2015-06-24 65 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);