laravel 4雄辩:一对多的结果导致奇怪的结果
我在这里遇到了一些关于拉威尔一对多关系的奇怪问题。我在用户和书籍之间有一对多的关系。当试图从视图中显示相关对象时,结果要么为无,要么为相关对象,具体取决于我如何访问它 用户模型laravel 4雄辩:一对多的结果导致奇怪的结果,laravel,laravel-4,Laravel,Laravel 4,我在这里遇到了一些关于拉威尔一对多关系的奇怪问题。我在用户和书籍之间有一对多的关系。当试图从视图中显示相关对象时,结果要么为无,要么为相关对象,具体取决于我如何访问它 用户模型 //User table: id, username, ... class User extends ConfideUser implements UserInterface, RemindableInterface { public function books(){ return $this-
//User table: id, username, ...
class User extends ConfideUser implements UserInterface, RemindableInterface {
public function books(){
return $this->hasMany("Book","user");
}
}
图书模型
//Book table: id, user, title...
class Book extends Ardent{
public function myUser(){
return $this->belongsTo("User","user"); //I name user_id field as "user"
}
}
视图:
您并没有告诉我们关于
ConfideUser
类,但基本上应该扩展
您可以使用(获取拥有书籍的用户)检查关系并获取结果
如果你这样问
$books = Book::all();
return View::make('books')->with('books', $books);
在视图中
可以使用
@foreach ($books as $book)
{{ $book->user->id }}
@endforeach
class Book extends Eloquent{
public function user(){
return $this->belongsTo("User", "user");
}
}
$books = Book::has('user')->get();
$books = Book::all();
return View::make('books')->with('books', $books);
@foreach ($books as $book)
{{ $book->user->id }}
@endforeach