Home Backend Development PHP Tutorial Learn Laravel5's Eloquent relationship

Learn Laravel5's Eloquent relationship

Dec 26, 2017 pm 01:26 PM
eloquent relation

Eloquent是Laravel的原始ActiveRecord是实现的,建立在Laravel的Fluent Query Builder之上的,所以Eloquent类和Fluent类是一样的,能实现复杂的SQL语句和非常直观表达出的表与表之间的关系。本文就以此展开学习,希望对大家有所帮助。

一个用户可能有多个文章,一个文章是某个用户书写的,这就是关系。同样文章中可能包含多个 TAG,而一个 TAG 可能关联多个文章。

在项目中,我们已经有了 User.php,也就是用户模型,查看一下,相当简单。我们希望直接使用 $user->articles() 的形式获取全部文章,让我们修改 user 模型:

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

但是我们仅仅完成了关系中的一端,让我们来处理另一端。我们希望的形式是 $article->user() ,让我们修改 article 模型。

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

在我们的数据库中,文章模型没有用户的外键,我们需要设置,修改 create_article_table.php

 Schema::create('articles', function(Blueprint $table)
 {
  $table->increments('id');
      //指定外键列
      $table->integer('user_id')->unsigned();
      $table->string('title');
      $table->text('body');
      $table->timestamp('published_at');
  $table->timestamps();

      //生成外键
      $table->foreign('user_id')
        ->references('id')
        ->on('users')
        ->onDelete('cascade');
 });
Copy after login

因为我们只是在开发阶段,还没有上线运行,我们可以直接修改数据库迁移文件,回滚然后迁移即可,但是如果上线运行的话,应该新建一个迁移。

php artisan migrate:refresh

#输出信息
Rolled back: 2015_03_28_050138_create_article_table
Rolled back: 2014_10_12_100000_create_password_resets_table
Rolled back: 2014_10_12_000000_create_users_table
Nothing to rollback.
Migrated: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_100000_create_password_resets_table
Migrated: 2015_03_28_050138_create_article_table
Migrated: 2015_03_28_051200_add_excerpt_to_articels_table
Copy after login

现在让我们使用 tinker 来创建一个用户。

php artisan tinker
Psy Shell v0.4.1 (PHP 5.4.16 — cli) by Justin Hileman

#下面是执行过程
>>> $user = new App\User;
=> <App\User #000000007f1ad61a000000006497cc4f> {}
>>> $user->name = &#39;zhang jinglin&#39;;
=> "zhang jinglin"
>>> $user->email = &#39;zjl@example.com&#39;;
=> "zjl@example.com"
>>> $user->password = bcrypt(&#39;pass&#39;);
=> "$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"
  ]
>>>
Copy after login

现在我们需要新发布的文章和用户关联,我们暂时先修改 form_partial.blade.php 来隐藏一个用户id,只是暂时:


复制代码 代码如下:


{{--临时处理--}}
{!! Form::hidden('user_id', 1) !!}

同时要修改模型的 $fillabel 属性,以便我们的 Mass Assisment。

 protected $fillable = [
    &#39;title&#39;,
    &#39;body&#39;,
    &#39;published_at&#39;,
    &#39;user_id&#39; //临时设置
  ];
Copy after login

OK,添加一个文章。我们使用 tinker 来查看一下。

php artisan tinker
Psy 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" => "2015-03-31 08:00:00",
    "created_at"  => "2015-03-31 04:17:58",
    "updated_at"  => "2015-03-31 04:17:58",
    "excerpt"   => null
  ]

#获取用户
>>> $user = App\User::first();
=> <App\User #0000000051cbb9d70000000073e11a3e> {
    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 &#39;Call to undefined method Illuminate\Database\Query\Builder::toArray()&#39;
>>> $user->articles->toArray();
=> [
    [
      "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
    ]
  ]
  
#为什么使用 $user->articles 而不是 #user->articles()?
#事实上,$user->articles()返回的是关系,如果你想用 articles() 你需要这样用
>>> $user->articles()->get()->toArray();
=> [
    [
      "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
    ]
  ]
  
#你只能使用 articles() 来进行下一步的工作,比如下面的查询

$user->articles()->where(&#39;title&#39;, &#39;User 1 Article&#39;)->get();

#我们也可以通过 article 获取 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",
    name: "zhang jinglin",
    email: "zjl@example.com",
    created_at: "2015-03-31 03:24:55",
    updated_at: "2015-03-31 03:24:55"
  }
>>>
Copy after login

相关推荐:

Laravel 关联模型由于名称一致性导致的问题 laravel 视频教程 thinkphp php laravel

PHP Laravel框架路由配置及设置技巧全解

laravel 学习笔记 —— 神奇的服务容器 laravel下载 yii php laravel

The above is the detailed content of Learn Laravel5's Eloquent relationship. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Implementation of optimistic locking in Laravel Eloquent model Implementation of optimistic locking in Laravel Eloquent model Apr 21, 2023 pm 03:53 PM

This article brings you relevant knowledge about Laravel. It mainly introduces to you the implementation of optimistic locking in the Laravel Eloquent model. There are code examples. Friends who are interested can take a look below. I hope it will be helpful to you.

Laravel development: How to implement polymorphic associations using Laravel Eloquent? Laravel development: How to implement polymorphic associations using Laravel Eloquent? Jun 13, 2023 pm 04:41 PM

Laravel development: How to use LaravelEloquent to implement polymorphic associations? Polymorphic association is an important feature of Laravel Eloquent, which allows one model to establish relationships with multiple different models. In practical applications, processing different types of data is relatively simple and efficient, especially in database design. In this article, we will discuss how to implement polymorphic associations using Laravel Eloquent. 1. What is a polymorphic association? Polymorphism

How to use Eloquent to convert array to object in Laravel? How to use Eloquent to convert array to object in Laravel? Apr 29, 2024 pm 05:42 PM

Converting an array into an object using Eloquent in Laravel requires the following steps: Create an Eloquent model. Use Eloquent's select method to get the result and convert it to an array. Use ArrayObject to convert an array into an object. Gets an object property to access an array's values.

Explore the relationship between the Android system and the Linux kernel Explore the relationship between the Android system and the Linux kernel Mar 14, 2024 pm 12:48 PM

The Android system and the Linux kernel are two closely related entities, and the relationship between them is close and complex. In the Android system, the Linux kernel plays an important role, providing underlying hardware drivers and system call support for the Android system. This article will explore the relationship between the Android system and the Linux kernel, how they interact and work together, and provide some specific code examples. Android is a mobile operating system developed based on the Linux kernel and is mainly used for mobile devices such as smartphones and tablets. L

Research on the relationship between Huawei Hongmeng system and Android Research on the relationship between Huawei Hongmeng system and Android Mar 23, 2024 am 11:54 AM

Research on the relationship between Huawei Hongmeng system and Android With the continuous development of technology, smartphones have become an indispensable part of people's lives. As one of the world's leading mobile phone manufacturers, Huawei has been constantly innovating and is committed to providing better mobile operating systems and user experiences. In recent years, with the United States' suppression of Huawei, Huawei has begun to accelerate the development of its own operating system, and HarmonyOS came into being. In this context, people have begun to pay attention to the relationship between Hongmeng System and Android. First, we need to understand

The relationship and use of equals(Object) method and hashCode() method in Java The relationship and use of equals(Object) method and hashCode() method in Java Jan 11, 2024 am 10:59 AM

The equals(Object) method and hashCode() method in Java are two important methods used to compare objects for equality. There is a close relationship and interdependence between them, and they play an important role in actual development. First, let's analyze the role of the equals(Object) method. The equals(Object) method is a method defined in the Object class, and all Java classes inherit from the Object class. equals(Obje

Laravel development: How to implement model association using Laravel Eloquent? Laravel development: How to implement model association using Laravel Eloquent? Jun 13, 2023 am 10:47 AM

Laravel is a popular PHP framework that includes the powerful ORM (Object Relational Mapping) library-LaravelEloquent. This library is very powerful and can help us easily implement model association, making it easier to manage and query data. But many developers don't know how to use Laravel Eloquent to implement model association. In this article, I will introduce how to implement model association using Laravel Eloquent. 1. Laravel

The relationship between default gateway and ip address The relationship between default gateway and ip address Feb 20, 2024 am 11:45 AM

The relationship between default gateway and IP address With the development of computer networks, we increasingly use the Internet to perform various activities, such as browsing the web, sending emails, conducting online transactions, etc. In this process, we often hear some network terms, such as IP address and default gateway. So, what is the relationship between IP address and default gateway? This article will analyze this issue in detail. First, we need to understand the concept of IP address. An IP address is an address that uniquely identifies a device on the Internet. It consists of 32 bits

See all articles