控制器中:
public getShow($id){$post=Post::find($id)return View::make('admin.post-detail')->with('posts',$post);}
在post模板中:
public function user(){ return $this->belongsTo('User');}
然後在post-detail.blade.php中可以這樣使用:$post->user ..
@foreach($posts as $post){{$post->user->username}}@endforeach
而posts表中並沒有user欄位 為什麼卻可以查詢出來結果?
回複內容:
控制器中:
public getShow($id){$post=Post::find($id)return View::make('admin.post-detail')->with('posts',$post);}
在post模板中:
public function user(){ return $this->belongsTo('User');}
然後在post-detail.blade.php中可以這樣使用:$post->user ..
@foreach($posts as $post){{$post->user->username}}@endforeach
而posts表中並沒有user欄位 為什麼卻可以查詢出來結果?
會在post表中找user_id欄位,如果您想定義一個不同的外鍵欄位,您可以通過 belongsTo 函數的第二個參數傳遞它:
class Phone extends Eloquent { public function user() { return $this->belongsTo('User', 'local_key'); }}
belongsTo()函數是 Laravel Eloquent 提供的模型間關係的一種,Post類由於繼承了 \Eloquent 類所以也可以調用。
模型間關係具體該如何使用可以參考:深入理解 Laravel Eloquent(三)——模型間關係(關聯)
請查看laravel的Eloquent ORM用法。
Defining The Inverse Of A Relation
phpclass Post extends Eloquent { public function user() { //$foreignKey預設為當前調用函數_id,即user_id,$otherKey為當前類主鍵id //select user_id from post where id=$post_id; //select username from user where user_id=$user_id; return $this->belongsTo('User', $foreignKey, $otherKey); }}