<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>laravel 基础教程 &#8211; 萧邦的博客</title>
	<atom:link href="https://www.zlhlab.top/tag/laravel-%E5%9F%BA%E7%A1%80%E6%95%99%E7%A8%8B/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.zlhlab.top</link>
	<description>If not me who, If not now when</description>
	<lastBuildDate>Thu, 26 Oct 2017 15:09:43 +0000</lastBuildDate>
	<language>zh-Hans</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.6</generator>
	<item>
		<title>laravel 基础教程 —— Eloquent</title>
		<link>https://www.zlhlab.top/laravel-%e5%9f%ba%e7%a1%80%e6%95%99%e7%a8%8b-eloquent/</link>
		
		<dc:creator><![CDATA[萧邦]]></dc:creator>
		<pubDate>Thu, 26 Oct 2017 15:09:43 +0000</pubDate>
				<category><![CDATA[技术]]></category>
		<category><![CDATA[laravel 基础教程]]></category>
		<guid isPermaLink="false">https://www.zlhlab.top/?p=415</guid>

					<description><![CDATA[Eloquent: 起步 简介简介 Laravel 的 Eloquent ORM 提供了一种漂亮简洁的关系映射<div class="more-link">
				 <a href="https://www.zlhlab.top/laravel-%e5%9f%ba%e7%a1%80%e6%95%99%e7%a8%8b-eloquent/" class="link-btn theme-btn"><span>Read More </span> <i class="fa fa-caret-right"></i></a>
			</div>]]></description>
										<content:encoded><![CDATA[<h3>Eloquent: 起步</h3>
<h4>简介简介</h4>
<p>Laravel 的 Eloquent ORM 提供了一种漂亮简洁的关系映射的模型来与数据库进行交互。所有的数据库表都有相应的模型，这些模型被用来与表进行交互。模型允许你直接查询数据库表中的数据，及插入新的记录到数据表中。</p>
<p>在开始之前，你需要确保完成了 <code>config/database.php</code> 配置文件中的数据库配置。对于更多的配置数据库相关的信息，请参考 <a href="https://laravel.com/docs/5.2/database#configuration" title="文档" target="_blank">文档</a>。</p>
<h4>定义模型</h4>
<p>在开始之前，让我们先来创建一个 Eloquent 模型。模型通常存放在 <code>app</code> 目录下，但是你也可以自由的放置在任何地方，只要它能够根据你的 <code>composer.json</code> 文件的指导进行自动的加载。所有的 Eloquent 模型都继承自 <code>Illuminate\Database\Eloquent\Model</code> 类。</p>
<p>最简单的创建一个模型类的方式就是使用 <code>make:model</code> Artisan 命令：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">php artisan make:model User
</code></pre>
<p>如果你希望在你生成模型的同时生成一份数据库迁移，你可以使用 <code>--migration</code> 或者 <code>-m</code> 选项：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">php artisan make:model User --migration

php artisan make:model User -m
</code></pre>
<h3>Eloquent 模型约定</h3>
<p>现在，让我们来看一个 Flight 模型的示例，我们将通过它获取和存储数据库中 flights 表的数据：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">&lt;?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Flight extends Model
{
  //
}
</code></pre>
<h4>表名称</h4>
<p>你需要注意我们上面的代码中并没有指出 <code>Flight</code> 模型使用哪个数据库的表。如果你没有明确的指出模型所对应的表，那么 Eloquent 将使用类的蛇形命名的复数形式来使用相应的数据表。所以，在这个例子中，Eloquent 将会假定 <code>Flight</code> 模型存储的记录被放在 <code>flights</code> 表中。你可以使用 <code>table</code> 属性来指定表名：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">&lt;?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Flight extends Model
{
  /**
   * The table associated with the model.
   *
   * @var string
   */
   protected $table = 'my_flights';
}
</code></pre>
<h4>主键</h4>
<p>Eloquent 也会假定所有表的主键列名为 <code>id</code>。你也可使用 <code>$primaryKey</code> 属性来手动的指定表的主键。</p>
<p>另外，Eloquent 也会假定主键是一个自增的整型值，这意味着，在默认情况下主键会被自动的转为 <code>int</code>。如果你希望使用非自增或者非数字的主键，那么你需要在模型中将公开的 <code>$incrementing</code> 属性设置为 <code>false</code>。</p>
<h4>时间戳</h4>
<p>默认的，Eloquent 期望模型表中存在 <code>created_at</code> 和 <code>updated_at</code> 列，如果你不希望 Eloquent 自主的管理这两列，你可以在模型中设置 <code>$timestamps</code> 属性为 <code>false</code>:</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">&lt;?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Flight extends Model
{
  /**
   * Indicates if the model should be timestamped.
   *
   * @var bool
   */
   public $timestamps = false;
}
</code></pre>
<p>如果你需要自定义时间戳的格式，你可以设置 <code>$dateFormat</code> 属性。这个属性用来决定日期属性存储在数据库中的格式，以及模型在进行序列化为数组或者 JSON 时的显示样式：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">&lt;?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Flight extends Model
{
  /**
   * The storage format of the model's date columns.
   *
   * @var string
   */
   protected $dateFormat = 'U';
}
</code></pre>
<h4>数据库连接</h4>
<p>默认的，所有的 Eloquent 模型都会使用应用配置的默认的数据库连接。如果你希望模型使用不同的数据库连接，你可以使用 <code>$connection</code> 属性：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">&lt;?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Flight extends Model
{
  /**
   * The connection name for the model.
   *
   * @var string
   */
   protected $connection = 'connection-name';
}
</code></pre>
<h3>检索多个模型</h3>
<p>一旦你创建了模型和其相应的数据表，你就为从数据库中检索数据做好了准备。你可以把 Eloquent 模型作为一个强大的查询生成器来使用，它允许通过模型流畅的查询相应的表中的数据。比如：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">&lt;?php

namespace App\Http\Controllers;

use App\Flight;
use App\Http\Controllers\Controller;

class FlightController extends Controller
{
  /**
   * Show a list of all available flights.
   *
   * @return Response
   */
  public function index()
  {
    $flights = Flight::all();

    return view('flight.index', ['flights' =&gt; $flights]);
  }
}
</code></pre>
<h4>访问列的值</h4>
<p>如果你获得了 Eloquent 模型的实例，那么你可以通过模型中相应的列名的属性来访问表中列的值。比如，让我们循环查询的结果，并通过获取的 <code>Flight</code> 实例来获得 <code>name</code> 列的值：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">foreach ($flights as $flight) {
  echo $flight-&gt;name;
}
</code></pre>
<h4>添加额外的条件</h4>
<p>Eloquent 的 <code>all</code> 方法会返回模型表中所有的记录。由于所有的 Eloquent 模型都可以作为查询生成器来进行服务，所以你可以在这些查询中增加额外的条件，然后使用 <code>get</code> 方法来检索结果：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">$flights = App\Flight::where('active', 1)
             -&gt;orderBy('name', 'desc')
             -&gt;take(10)
             -&gt;get();
</code></pre>
<blockquote><p>
  注意：由于 Eloquent 模型也是查询生成器，所以你可以回顾一下查询生成器中所有可用的方法，因为它们同样可以在 Eloquent 中进行使用。
</p></blockquote>
<h4>集合</h4>
<p>对于像 <code>all</code> 和 <code>get</code> 这样的 Eloquent 方法会返回多个结果，这将返回一个 <code>Illuminate\Database\Eloquent\Collection</code> 实例。<code>Collection</code> 类提供了各种有用的方法与 Eloquent 结果进行交互。当然，你可以简单的对集合进行循环，因为他实现了 ArrayAccess 接口：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">foreach ($flights as $flight) {
  echo $flight-&gt;name;
}
</code></pre>
<h4>对结果进行分块</h4>
<p>如果你需要处理数千条 Eloquent 记录，那么你可以使用 <code>chunk</code> 方法。<code>chunk</code> 方法会从 Eloquent 模型中检索出一小块记录，然后将其传递给 <code>Closure</code> 进行处理。使用 <code>chunk</code> 方法在处理大量结果集时可有有效的降低内存的消耗：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">Flight::chunk(200, function ($flights) {
  foreach ($flights as $flight) {
    //
  } 
});
</code></pre>
<p>传递到方法的第一个参数是你要设置进行分块的大小。而传递到第二个参数的闭包将会在从数据库检索出每块内容时进行调用。</p>
<h3>检索单个模型 / 统计</h3>
<p>当然，除了可以从表中检索出所有的记录之外，你也可以使用 <code>find</code> 和 <code>first</code> 方法来从数据库中检索出单条的数据。这将会返回一个单独的模型实例：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">// Retrieve a model by its primary key...
$flight = App\Flight::find(1);

// Retrieve the first model matching the query constraints...
$flight = App\Flight::where('active', 1)-&gt;first();
</code></pre>
<p>你也可以使用 find 方法时传递一个包含主键所组成的数组，这将返回所有匹配到记录的集合：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">$flights = App\Flight::find([1, 2, 3]);
</code></pre>
<h4>未发现时的异常</h4>
<p>有时候，你可能希望在没有找到匹配的模型时抛出一个异常。这对路由或者控制器来说尤其有用。<code>findOrFail</code> 和 <code>firstOrFail</code> 方法可以从查询中检索出首个匹配的结果，但是，如果结果中没有匹配的项，那么会抛出一个 <code>Illuminate\Database\Eloquent\ModelNotFoundException</code> 异常：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">$model = App\Flight::findOrFail(1);

$model = App\Flight::where('legs', '&gt;', 100)-&gt;firstOrFail();
</code></pre>
<p>如果异常没有被捕获，那么会直接传递给用户一个 <code>404</code> HTTP 响应。所以当你在使用这些方法时是没有必要编写明确的检查并返回 <code>404</code> 响应的：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">Route::get('/api/flights/{id}', function ($id) {
  return App\Flight::findOrFail($id); 
});
</code></pre>
<h4>检索统计</h4>
<p>当然，你可以使用 <code>count</code>，<code>sum</code>，<code>max</code> 和其他 <a href="https://laravel.com/docs/5.2/queries" title="查询生成器" target="_blank">查询生成器</a> 所提供的的 <a href="https://laravel.com/docs/5.2/queries#aggregates" title="聚合函数" target="_blank">聚合函数</a>。这些方法会返回适当的数值，而不是完整的模型实例：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">$count = App\Flight::where('active', 1)-&gt;count();

$max = App\Flight::where('active', 1)-&gt;max('price');
</code></pre>
<h3>插入 &amp; 更新模型</h3>
<h4>基础插入</h4>
<p>想要在数据库中插入新的记录，只需要简单的创建模型实例，然后设置模型的属性，再调用 <code>save</code> 方法就可以了：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">&lt;?php

namespace App\Http\Controllers;

use App\Flight;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class FlightController extends Controller
{
  /**
   * Create a new flight instance.
   *
   * @param Request $request
   * @return Response
   */
   public function store(Request $request)
   {
     // Validate the request...

     $flight = new Flight;

     $flight-&gt;name = $request-&gt;name;

     $flight-&gt;save();
   }
}
</code></pre>
<p>在这个例子中，我们简单的从流入的 HTTP 请求中的 <code>name</code> 参数分配到 <code>App\Flight</code> 模型实例的 <code>name</code> 属性上。当我们调用 <code>save</code> 方法时，这条记录将会插入到数据库中，同时 <code>created_at</code> 和 <code>updated_at</code> 时间戳也会自动的被进行设置，所以这并不需要进行手动的设置它们。</p>
<h4>基础的更新</h4>
<p><code>save</code> 方法也可用来更新数据库中已经存在的数据模型。为了更新模型，你应该首先检索到它们，然后设置任何你想要更新的属性，接着调用 <code>save</code> 方法。这一次，<code>updated_at</code> 时间戳会自动的进行更新，所以你并不需要手动的更新这个值：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">$flight = App\Flight::find(1);

$flight-&gt;name = 'New Flight Name';

$flight-&gt;save();
</code></pre>
<p>你也可以针对查询匹配的多个模型进行更新操作。比如，所有 <code>active</code> 并且 <code>destination</code> 为 <code>San Diego</code> 的航班将会被标记为延迟：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">App\Flight::where('active', 1)
          -&gt;where('destination', 'San Diego')
          -&gt;update(['delayed' =&gt; 1]);
</code></pre>
<p><code>update</code> 方法接收一个想要更新的列的键值对数组。</p>
<h4>批量赋值</h4>
<p>你也可以使用 <code>create</code> 方法来在一行中存储一个新的模型。一个新增的模型实例将会从方法中返回。事实上，在开始做这些之前，你需要先指定模型的 <code>fillable</code> 或者 <code>guarded</code> 属性，它们是针对批量赋值时的保护措施。</p>
<p>当用户通过 HTTP 请求传递一些意外的参数时，这可能会造成批量赋值时一些问题的出现，或许参数中存在一些你并不想改变的列值的参数。比如，一个恶意的用户可能会在请求中嵌入一个 <code>is_admin</code> 参数，然后这些参数映射到你的 <code>create</code> 方法中，这就使用户将自己升级为了超级管理员。</p>
<p>所以，在开始之前，你需要先定义哪些模型属性是可以进行批量分配的。你可以使用模型 <code>$fillable</code> 属性，让我们在 <code>Flight</code> 模型中添加允许 <code>name</code> 属性的批量赋值：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">&lt;?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Dlight extends Model
{
  /**
   * The attributes that are mass assignable.
   *
   * @var array
   */
   protected $fillable = ['name'];
}
</code></pre>
<p>一旦我们使一个属性可以进行批量赋值。那么我们可以使用 <code>create</code> 方法直接的添加记录到数据中。<code>create</code> 方法会返回存储后的模型实例：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">$flight = App\Flight::create(['name' =&gt; 'Flight 10']);
</code></pre>
<p>而 <code>$fillable</code> 就像是为批量赋值提供了一种白名单的机制。你也可以选择使用 <code>$guarded</code>。<code>$guarded</code> 属性应该包含一个你不想要进行批量赋值的属性所组成的数组。所有不在这个数组中的属性都将可以进行批量赋值。所以，<code>$guarded</code> 就像一个黑名单的功能。当然，你应该只使用 <code>$fillable</code> 或者 <code>$guarded</code> 中的一个，而不是全部：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">&lt;?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Flight extends Model
{
  /**
   * The attributes that aren't mass assignable.
   *
   * @var array
   */
   protected $guarded = ['price'];
}
</code></pre>
<p>在上面的例子中，除了 <code>price</code>，所有的属性都可以进行批量赋值。</p>
<p>其他创建方法</p>
<p>这里也有其他两种方法可以使用批量赋值进行模型的创建：<code>firstOrCreate</code> 和 <code>firstOrNew</code>。<code>firstOrCreate</code> 方法会尝试根据给定的列的键值对从数据库定位相关的模型。如果相关的模型没有找到，那么会根据给定的属性在数据库中新增一条记录。</p>
<p><code>firstOrNew</code> 方法和 <code>firstOrCreate</code> 方法一样，但是它在模型没找到时只会返回一个新的模型实例，并不会在数据库中新增一条记录。你需要手动的使用 save 方法来将其存储到数据库中：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">// Retrieve the flight by the attributes, or create it if it doesn't exists...
$flight = App\Flight::firstOrCreate(['name' =&gt; 'Flight 10']);

// Retrieve the flight by the attributes, or instantiate a new instance...
$flight = App\Flight::firstOrNew(['name' =&gt; 'Flight 10']);
</code></pre>
<h3>删除模型</h3>
<p>你可以在模型实例中使用 delete 方法来删除模型：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">$flight = App\Flight::find(1);

$flight-&gt;delete();
</code></pre>
<h4>根据键删除存在的模型</h4>
<p>在上面的例子中，我们先从数据库中检索出相关的模型，然后才调用 delete 方法来进行删除。事实上，如果你知道了模型的主键，那么你完全可以不用去检索到它。你可以直接使用 destroy 方法来进行删除：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">App\Flight::destroy(1);

App\Flight::destroy([1, 2, 3]);

App\Flight::destroy(1, 2, 3);
</code></pre>
<h4>通过查询删除模型</h4>
<p>当然，你也可以通过查询删除一个模型集。在这个例子中，我们将删除所有标记为未启用的航班：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">$deletedRows = App\Flight::where('active', 0)-&gt;delete();
</code></pre>
<h4>软删除</h4>
<p>除了从数据库中真实的删除数据之外，Eloquent 也可以进行软删除操作。当模型是一个软删除模型时，它们并不会真正的从数据库中清除记录。实际上，它们会将模型的 <code>deleted_at</code> 属性进行设置，并且将其更新到数据库中。如果模型中的 <code>deleted_at</code> 的值不是 NULL，那么它就被标记为软删除了。如果你需要启用软删除模型，你需要在模型中引入 <code>Illuminate\Database\Eloquent\SoftDeletes</code> trait，并且在模型的 <code>$dates</code> 属性中添加 <code>deleted_at</code> 列：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">&lt;?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Flight extends Model
{
  use SoftDeletes;

  /**
   * The attributes that should be mutated to dates.
   *
   * @var array
   */
   protected $dates = ['deleted_at'];
}
</code></pre>
<p>当然，你应该在数据表中添加 <code>deleted_at</code> 列。<code>Laravel</code> 的 结构生成器 中提供了生成该列的方法:</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">Schema::table('flights', function ($table) {
  $table-&gt;softDeletes(); 
});
</code></pre>
<p>现在，当我们调用 <code>delete</code> 方法时，<code>deleted_at</code> 列会被设置为当前时间。并且，当查询启用软删除的模型时，已经被软删除的模型将自动从结果中剔除。</p>
<p>你可以使用 <code>trashed</code> 方法来判断所给定的模型是否已经被软删除：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">if ($flight-&gt;trashed()) {
  //
}
</code></pre>
<h3>查询软删除的模型</h3>
<h4>包含软删除的模型</h4>
<p>就如上面我们所提到的，被软删除的模型将自动的从结果中进行剔除。事实上，你可以使用 <code>withTrashed</code> 方法来强制结果中显示已经被软删除的模型：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">$flights = App\Flight::withTrashed()
             -&gt;where('account_id', 1)
             -&gt;get();
</code></pre>
<p><code>whitTrashed</code> 方法也可以在关联查询中进行使用：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">$flight-&gt;history()-&gt;withTrashed()-&gt;get();
</code></pre>
<h4>只检索被软删除的模型</h4>
<p><code>onlyTrashed</code> 方法会从数据库中检索被软删除的模型记录：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">$flights = App\Flight::onlyTrashed()
             -&gt;where('airline_id', 1)
             -&gt;get();
</code></pre>
<h4>还原被软删除的模型</h4>
<p>有时候你可能会希望还原已经被软删除的模型，你可以使用 restore 方法来将模型从软删除中解除：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">$flight-&gt;restore();
</code></pre>
<p>你也可以在查询中使用 restore 方法来快速的重启多个模型：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">App\Flight::withTrashed()
  -&gt;where('airline_id', 1)
  -&gt;restore();
</code></pre>
<p>就像 <code>withTrashed</code> 方法一样，<code>restore</code> 方法也可以在关联查询中使用：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">$flight-&gt;history()-&gt;restore();
</code></pre>
<h4>永久的删除模型</h4>
<p>有时候你可能希望从数据库中直接删除这个模型。你可以使用 <code>forceDelete</code> 方法来将模型从数据库中永久的删除：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">// Force deleting a single model instance...
$flight-&gt;forceDelete();

// Force deleting all related modls...
$flight-&gt;history()-&gt;forceDelete();
</code></pre>
<h3>查询区间</h3>
<h4>全局区间</h4>
<p>全局区间允许你在给定的模型上的所有查询进行约束的添加。Laravel 自己的软删除功能就是利用了全局区间来从数据库中拉取未删除的数据。编写自己的全局区间可以方便的对给定模型的所有查询进行约束。</p>
<h5>编写全局区间</h5>
<p>编写一个全局区间非常简单，你只需要定义一个实现了 <code>Illuminate\Database\Eloquent\Scope</code> 接口的类。这个接口只要求你实现一个方法：<code>apply</code>。<code>apply</code> 方法可以在需要的时添加 <code>where</code> 约束：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">&lt;?Php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class AgeScope implements Scope
{
  /**
   * Apply the scope to a given Eloquent query builder.
   *
   * @param \Illuminate\Database\Eloquent\Builder $builder
   * @param \Illuminate\Database\Eloquent\Model $model
   * @return void
   */
   public function apply(Builder $builder, Model $model)
   {
     return $builder-&gt;where('age', '&gt;', 200);
   }
}
</code></pre>
<p>Laravel 没有为区间预置存放的目录，所以你可以自由的创建自己的 <code>Scopes</code> 目录来进行管理。</p>
<h5>应用全局区间</h5>
<p>你需要在给定的模型中复写 <code>boot</code> 方法并且使用 <code>addGlobalScope</code> 方法来分配全局区间：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">&lt;?php

namespace App;

use App\Scopes\AgeScope;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
  /**
   * The "booting" method of the model
   *
   * @return void
   */
   protected static function boot()
   {
     paraent::boot();

     static::addGlobalScope(new AgeScope);
   }
}
</code></pre>
<p>在添加完区间之后，调用 <code>User::all()</code> 的查询会产生下述的 SQL：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-sql">select * from `users` where `age` &gt; 200
</code></pre>
<h5>匿名全局区间</h5>
<p>Eloquent 也允许你通过一个闭包来定义全局区间，这通常对于不需要分离到单独一个类文件中的简单区间尤其有用：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">&lt;?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class User extends Model
{
  /**
   * The "booting" method of the model.
   *
   * @return void
   */
   protected static function boot()
   {
     parent::boot();

     static::addGlobalScope('age', function (Builder $builder) {
       $builder-&gt;where('age', '&gt;', 200);
     });
   }
}
</code></pre>
<p>传递到 <code>addGlobalScope()</code> 方法的首个参数将作为区间的唯一标识，你可以通过标识将其排除：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">User::withoutGlobalScope('age')-&gt;get();
</code></pre>
<h5>删除全局区间</h5>
<p>如果你希望从给定的查询中移除全局区间，你可以使用 <code>withoutGlobalScope</code> 方法：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">User::withoutGlobalScope(AgeScope::class)-&gt;get();
</code></pre>
<p>如果你希望删除多个或者全部的全局区间，你可以使用这么使用 <code>withoutGlobalScopes</code> 方法：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">User::withoutGlobalScopes()-&gt;get();

User::withoutGlobalScopes([FirstScope::class, SecondScope::class])-&gt;get();
</code></pre>
<h4>当前区间</h4>
<p>当前区间允许你在模型中定义一些可以复用的常用的约束。比如，你可能经常需要检索一些受欢迎的用户。你可以简单的在模型方法中前置 <code>scope</code> 命名来定义一个区间.</p>
<p>区间应该总是返回一个查询生成器的实例：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">&lt;?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
  /**
   * Scope a query to only include popular users.
   *
   * @return \Illuminate\Database\Eloquent\Builder
   */
   public function scopePopular($query)
   {
     return $query-&gt;where('votes', '&gt;', 100);
   }

   /**
    * Scope a query to only include active users.
    *
    * @return \Illuminate\Database\Eloquent\Builder
    */
    public function scopePopular($query)
    {
      return $query-&gt;where('votes', '&gt;', 100);
    }

    /**
     * Scope a query to only include active users.
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
     public function scopeActive($query)
     {
       return $query-&gt;where('active', 1);
     }
}
</code></pre>
<h5>利用区间查询</h5>
<p>一旦区间进行了定义，你可以在模型进行查询时调用区间方法，事实上，你在调用区间方法时并不需要包含 <code>scope</code> 前缀。你甚至可以链式的调用其它的区间：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">$users = App\User::popular()-&gt;active()-&gt;orderBy('created_at')-&gt;get();
</code></pre>
<h4>动态区间</h4>
<p>有时候你可能希望定义一个可以接收参数的区间。在开始之前，你仅仅只需要在你的区间中添加一些额外的参数。区间参数应该在 <code>$query</code> 参数之后进行定义：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">&lt;?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
  /**
   * Scope a query to only include users of a given type.
   *
   * @return \Illuminate\Database\Eloquent\Builder
   */
   public function scopeOfType($query, $type)
   {
     return $query-&gt;where('type', $type);
   }
}
</code></pre>
<p>现在，你可以在调用区间时传递一些参数了：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">$users = App\User::ofType('admin')-&gt;get();
</code></pre>
<h3>事件</h3>
<p>Eloquent 模型可以触发多种事件，这允许你在模型的生命周期的各个关键点进行 hook 操作。你可以使用下面的方法进行 Hook：<code>creating</code>，<code>created</code>，<code>updating</code>，<code>updated</code>，<code>saving</code>，<code>saved</code>，<code>deleting</code>，<code>deleted</code>，<code>restoring</code>，<code>restored</code>。事件允许你轻松的在模型进行存储或更新操作时进行执行额外的操作。</p>
<h4>基础用法</h4>
<p>当一个新的模型首次进行存储操作时，会触发 <code>creating</code> 和 <code>created</code> 事件。如果模型已经存在于数据库中，并且调用 <code>save</code> 方法，那么 <code>updating</code> / <code>updated</code> 事件将会被触发。事实上，在这两种情况下，<code>saving</code> 和 <code>saved</code> 事件都会被触发。</p>
<p>举个示例，让我们在服务提供者中定义一个 Eloquent 事件监听器。在我们的事件监听器中，我们将在给定的模型中调用 <code>isValid</code> 方法，当模型并没有通过验证时将返回 <code>false</code>。如果从 Eloquent 事件监听器中返回 <code>false</code>，那么将取消 <code>save</code> / <code>update</code> 操作：</p>
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-php">&lt;?php

namespace App\Providers;

use App\User;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
  /**
   * Bootstrap any application services.
   *
   * @return void
   */
   public function boot()
   {
     User::creating(function ($user) {
       if (! $user-&gt;isValid()) {
         return false;
       }
     });
   }

   /**
    * Register the service provider.
    *
    * @return void
    */
    public function register()
    {
      //
    }
}
</code></pre>
<p>作者：Dearmadman<br />
链接：http://www.jianshu.com/p/98e5de87816d<br />
來源：简书<br />
著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
