laravel中資料庫表得關聯問題

來源:互聯網
上載者: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欄位 為什麼卻可以查詢出來結果?

回複內容:

控制器中:

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);    }}
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.