Database tables in Laravel related issues

Source: Internet
Author: User
In the controller:

public getShow($id){$post=Post::find($id)return View::make('admin.post-detail')->with('posts',$post);}

In the post template:

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

You can then use this in post-detail.blade.php: $post->user.

@foreach($posts as $post){{$post->user->username}}@endforeach

And there is no user field in the posts table. Why can I query the results?

Reply content:

In the controller:

public getShow($id){$post=Post::find($id)return View::make('admin.post-detail')->with('posts',$post);}

In the post template:

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

You can then use this in post-detail.blade.php: $post->user.

@foreach($posts as $post){{$post->user->username}}@endforeach

And there is no user field in the posts table. Why can I query the results?

The user_id field is found in the post table, and if you want to define a different foreign key field, you can pass it through the second parameter of the Belongsto function:

class Phone extends Eloquent {    public function user()    {        return $this->belongsTo('User', 'local_key');    }}

belongsTo()A function is one of the relationships between models provided by Laravel eloquent, and Post classes \Eloquent can also be called because they inherit the class.

The relationship between models can be used as a reference: in-depth understanding of Laravel eloquent (iii)--Model Relationship (association)

See the eloquent ORM usage of laravel.

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);    }}
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    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.