Laravel5 basics (11)-Eloquent relationship

Source: Internet
Author: User
: This article mainly introduces Laravel5 basics (11)-Eloquent relationships. For more information about PHP tutorials, see. A user may have multiple articles. one article is written by a user. this is the relationship. The same article may contain multiple tags, and one TAG may be associated with multiple articles.

In the project, we already haveUser.php, That is, the user model. it is quite simple. We want to directly use$user->articles()To get all the articles, let's modify the user model:

    public function articles() {        return $this->hasMany('App\Article');    }

But we only completed one end of the link. let's deal with the other end. The expected form is$article->user(), Let's modify the article model.

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

In our database, the document model does not have a user's foreign key, so we need to set, modifycreate_article_table.php

Schema: create ('articles', function (Blueprint $ table) {$ table-> increments ('id '); // specify the foreign key column $ table-> integer ('User _ id')-> unsigned (); $ table-> string ('title '); $ table-> text ('body'); $ table-> timestamp ('hhed _ at'); $ table-> timestamps (); // Generate a foreign key $ table-> foreign ('User _ id')-> references ('id')-> on ('users ') -> onDelete ('cascade ');});

Because we are only in the development stage and haven't been online yet, we can directly modify the database migration file, roll back and migrate it. but if it is online, we should create a new migration.

Php artisan migrate: refresh # Rolled back: rollback back: Failed to rollback. Migrated: 2014_10_12_000000_create_users_tableMigrated: Pushed

Now let's usetinkerCreate a user.

Php artisan tinkerPsy Shell v0.4.1 (PHP 5.4.16-cli) by Justin Hileman # The following is the execution process >>>$ user = new App \ User; >{}>>>$ user-> name = 'Zhang Jinglin'; => "zhang jinglin" >>>$ user-> email = 'zjl @ example.com '; => "zjl@example.com" >>>$ user-> password = bcrypt ('pass'); => "$ 2y $10 $ Nbl2b9wqd. rxqkesd3prsooiyfafihb%71bufwdfs3guv21slex2 ">>>$ user-> save () ;=> true >>> App \ User: first ()-> toArray (); => ["id" => "1", "name" => "zhang jinglin", "email" => "zjl@example.com ", "created_at" => "03:24:55", "updated_at" => "03:24:55"]>

Now we need to associate the newly published article with the user. now we need to modifyform_partial.blade.phpTo hide a user ID, but temporarily:

{-- Temporary processing --}}{!! Form: hidden ('User _ id', 1 )!!}

The$fillabelAttribute to facilitate our Mass Assisment.

Protected $ fillable = ['title', 'body', 'hhed _ at', 'User _ id' // temporary settings];

OK. add an article. We usetinkerTo view.

Php artisan tinkerPsy Shell v0.4.1 (PHP 5.4.16-cli) by Justin Hileman >>> App \ Article: first ()-> toArray (); => ["id" => "1", "user_id" => "1", "title" => "User 1 Article ", "body" => "User 1 Body", "published_at" => "08:00:00", "created_at" => "04:17:58 ", "updated_at" => "04:17:58", "excerpt" => null] # get a user >>>$ User = App \ user: first () ;=>{ id: "1", name: "zhang jing Lin ", email:" zjl@example.com ", created_at:" 03:24:55 ", updated_at:" 03:24:55 "} # get user articles >>>> $ user-> articles () -> toArray (); BadMethodCallException with message 'Call to undefined method Illuminate \ Database \ Query \ Builder: toArray () '>>>> $ user-> articles-> toArray () ;=> [["id" => "1", "user_id" => "1 ", "title" => "User 1 Article", "body" => "User 1 Body", "published_at" => "2015-03-3 1 08:00:00 "," created_at "=>" 04:17:58 "," updated_at "=>" 04:17:58 ", "excerpt" => null] # Why use $ user-> articles instead of # user-> articles ()? # In fact, $ user-> articles () returns a link. if you want to use articles (), you need to use >>>$ user-> articles ()-> get () -> toArray (); => [["id" => "1", "user_id" => "1", "title" => "User 1 Article ", "body" => "User 1 Body", "published_at" => "08:00:00", "created_at" => "04:17:58 ", "updated_at" => "04:17:58", "excerpt" => null] # you can only use articles () for the next step, for example, the following query $ user-> articles ()-> where ('title', 'user 1 article')-> get (); # You can also get user >>$ article = App \ article: first () ;=>{ id: "1", user_id: "1", title: "User 1 Article", body: "User 1 Body", published_at: "08:00:00", created_at: "04:17:58", updated_at: "04:17:58", excerpt: null >>>>$ article-> user ;=>{ id: "1", name: "zhang jinglin", email: "zjl@example.com", created_at: "03:24:55 ", updated_at: "03:24:55" >>>

The above section describes Laravel 5 basics (11)-Eloquent relationships, including related content, and hopes to help those who are interested in PHP tutorials.

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.