4

我已经被困了一个小时,因为我试图找出 Laravel 5.2 在哪里得到 references() 方法代码如下所示

Schema::create('articles', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('user_id');
        $table->string('title');
        $table->text('body');
        $table->text('excerpt')->nullable();
        $table->timestamps();
        $table->timestamp('published_at');

        $table->foreign('user_id')->references('id')->on('users');
});

我似乎无法在 \Illuminate\Database\Schema\Blueprint 或 Illuminate\Support\Fluent 中找到 references() 方法。

谁能指出我在哪里可以找到上述代码中的 references() 方法?

任何帮助和提示都会很棒

4

2 回答 2

6

看起来它是由 Fluent 通过__call魔术方法处理的。

Laravel API - 流畅的@__call

任何不存在(或不可访问)的方法调用都将被传递给__call该方法调用,该方法调用将由方法命名的属性设置为您传递的值。

例子

$f = new \Illuminate\Support\Fluent;
$f->something('value')->willBeTrue();

dump($f);
//
Illuminate\Support\Fluent {
  #attributes: array:2 [
    "something" => "value"
    "willBeTrue" => true
  ]
}
于 2015-12-29T08:04:36.310 回答
2

当我打开 Blueprint 类并看到它使用 Fluent 时,我发现了与 lagbox 相同的东西,它实现了几个合同,其中包括 Arrayable 和 Jsonable,实际上任何不存在的方法都会传递给 __call 方法,它会创建一个属性数组中的新元素,键为方法名称:

$this->attributes[$method] = count($parameters) > 0 ? $parameters[0] : true;

但我仍然会扩展这个问题:在数据库记录上创建外键约束时,它在哪里真正使用了该属性?我知道深入研究并不会真正有用,但我发现自己真的很好奇 Schema 构建器除了捕获这些方法之外是如何工作的。

另一个值得一提的是像 onDelete('cascade') 这样的触发器,通常在这种情况下使用。

于 2016-07-25T19:29:15.643 回答