Laravel5 framework learning-Eloquent relation-php instance

Source: Internet
Author: User
Eloquent is implemented by the original ActiveRecord of Laravel and is built on FluentQueryBuilder of Laravel. Therefore, the Eloquent class is the same as the Fluent class, it can implement complex SQL statements and intuitively express the relationship between tables. One user may have multiple articles, and 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 have User. php, that is, the User model. It is quite simple to check. We want to get all the articles in the form of $ user-> 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 format 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. We need to set and modify create_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 use tinker to create 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. For the moment, we need to modify form_partial.blade.php to hide a user ID, but for the moment:

The Code is as follows:


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

At the same time, we need to modify the $ fillabel attribute of the model for our Mass Assisment.

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

OK. add an article. We can use tinker to check the problem.

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 is all the content of this article. I hope you will like it.

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.