The eloquent relationship of learning Laravel5

Source: Internet
Author: User
Eloquent is Laravel's original ActiveRecord is implemented, built on the Laravel fluent Query builder, so the eloquent class and the fluent class are the same, can implement complex SQL statements and very visually express the relationship between tables and tables. This article on this to start learning, I hope to be helpful to everyone.

A user may have multiple articles, an article written by a user, which is a relationship. The same article may contain multiple tags, while a tag may have multiple articles associated with it.

In the project, we already have the user.php, which is the user model, to look at, rather simple. We want to get all the articles directly in the form of $user->articles (), let's modify the user model:

  Public Function articles () {    return $this->hasmany (' app\article ');  }

But we just finished one end of the relationship, let's deal with the other end. The form we want is $article->user (), let's modify the article model.

  Public Function User () {    return $this->belongsto (' App\user ');  }

In our database, the article model does not have the user's foreign key, we need to set up, modify create_article_table.php

Schema::create (' articles ', function (Blueprint $table) {  $table->increments (' id ');      Specifies the foreign key column      $table->integer (' user_id ')->unsigned ();      $table->string (' title ');      $table->text (' body ');      $table->timestamp (' published_at ');  $table->timestamps ();      Generate foreign Key      $table->foreign (' user_id ')        ->references (' id ')        ->on (' users ')        ->ondelete (' Cascade '); });

Because we are only in the development phase, not yet on-line operation, we can directly modify the database migration files, roll back and then migrate, but if you run on-line, you should create a new migration.

PHP Artisan migrate:refresh# Output information rolled back:2015_03_28_050138_create_article_tablerolled back:2014_10_12_100000_ create_password_resets_tablerolled back:2014_10_12_000000_create_users_tablenothing to rollback. Migrated:2014_10_12_000000_create_users_tablemigrated:2014_10_12_100000_create_password_resets_tablemigrated: 2015_03_28_050138_create_article_tablemigrated:2015_03_28_051200_add_excerpt_to_articels_table

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;=> < ; App\user #000000007f1ad61a000000006497cc4f > {}>>> $user->name = ' Zhang Jinglin ';=> ' Zhang Jinglin ' >>> $user->email = ' zjl@example.com ';=> "zjl@example.com" >>> $user->password = Bcrypt (' Pass ');=> "$2y$10$nbl2b9wqd.rxqkesd3prsooiyfafihbqf71bufwdfs3guv21slex2" >>> $user->save ();=> True>>> App\user::first ()->toarray ();=> [    "id"     = "1",    "name" +    "Zhang" Jinglin ",    " email "   =" zjl@example.com ",    " created_at "=" 2015-03-31 03:24:55 ",    " updated_at "= > "2015-03-31 03:24:55"  ]>>>

Now that we need new posts and user associations, we will temporarily modify form_partial.blade.php to hide a user ID, but temporarily:


Copy the Code code as follows:


{---temporary processing--}}
{!! Form::hidden (' user_id ', 1)!!}

Also modify the $fillabel properties of the model so that our Mass assisment.

protected $fillable = [    ' title ',    ' body ', '    published_at ',    ' user_id '//temporary settings  ];

OK, add an article. Let's take a look at it using Tinker.

PHP artisan tinkerpsy Shell v0.4.1 (php 5.4.16-cli) by Justin hileman>>> App\article::first ()->toarray (); =&G T ["id" = "1", "user_id" = "1", "title" = "User 1 article", "body" = "User 1 Body" "," published_at "=" 2015-03-31 08:00:00 "," created_at "=" 2015-03-31 04:17:58 "," Updated_at "and" 20 15-03-31 04:17:58 "," excerpt "= null] #获取用户 >>> $user = App\user::first ();=> <app\user #0000000051  cbb9d70000000073e11a3e> {ID: "1", Name: "Zhang Jinglin", Email: "Zjl@example.com", Created_at: "2015-03-31 03:24:55 ", Updated_at:" 2015-03-31 03:24:55 "} #获取用户文章 >>> $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" and "=" "User 1 Body", "published_at" = "2015-03-31 08:00:00", "created_at" = "2015-03-31 04:17:58", "upd Ated_at "=" 2015-03-31 04:17:58 "," excerpt "+ NULL]] #为什么使用 $user->articles instead of #user->articl Es ()? #事实上, $user->articles () returns the relationship if you want to use articles () you need to do this with >>> $user->articles ()->get ()      ToArray ();=> [["id" = "1", "user_id" and "1", "title" = "User 1 article", "Body" = "User 1 Body", "published_at" and "2015-03-31 08:00:00", "created_at" and "=" 2015-03-31 04:1 7:58 "," updated_at "=" 2015-03-31 04:17:58 "," excerpt "and Null]] #你只能使用 articles () for the next step, such as The following query $user->articles ()->where (' title ', ' User 1 article ')->get (); #我们也可以通过 article get user>>> $    Article = App\article::first ();=> <app\article #0000000051cbb9d60000000073e11a3e > {id: "1", user_id: "1", Title: "User 1 article", Body: "User 1 body", Published_at:" 2015-03-31 08:00:00 ", Created_at:" 2015-03-31 04:17:58 ", Updated_at:" 2015-03-31 04:17:58 ", Excerpt:null}>>> $article->user;=> <app\user #0000000051cbb92d0000000073e11a3e > {id: "1", N Ame: "Zhang Jinglin", Email: "Zjl@example.com", Created_at: "2015-03-31 03:24:55", Updated_at: "2015-03-31 03:24: "}>>>

Related recommendations:

Laravel Association model issues due to name consistency Laravel video tutorial thinkphp php Laravel

PHP Laravel Framework routing configuration and setup techniques full solution

Laravel Study notes-the Magical service container laravel download yii php laravel

Related Article

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.