2017-07-07 7 views
1

は(括弧なし)laravelモデルの関係はどのようにコアで動作しますか?

class SomeClass extends Model{ 
    public function user(){ 
     return $this->belongsTo('App\User'); 
    } 
} 
$instance = SomeClass::findOrFail(1); 
$user = $instance->user; 

どのように行うlaravelノウハウ(私はコアの平均)$ instance->ユーザー復帰関連のモデルの例を考えてみましょうか?

+0

非常に幅広く、要約すると、 'Model.php'の' __get() 'アクセサで解決します。ソースコードを確認してください。 –

+0

はい。 Laravelのソースコードはオープンソースです。あなた自身でこれを調べることができます:https://github.com/laravel/framework/blob/5.4/src/Illuminate/Database/Eloquent/Model.php#L1260 –

+0

その魔法(機能)。 – apokryfos

答えて

4

基本的に、あなたはモデルからプロパティにアクセスしようとするたびに、__getmagic methodが呼び出されると、それは次のようなものです:あなたが__get魔法のメソッドが定義されている別のユーザーを呼び出す、ということ見ることができるように

public function __get($key) 
{ 
    return $this->getAttribute($key); 
} 

次のようなものである方法(getAttribute):(リレーションのため)この場合

public function getAttribute($key) 
{ 
    if (! $key) { 
     return; 
    } 

    // If the attribute exists in the attribute array or has a "get" mutator we will 
    // get the attribute's value. Otherwise, we will proceed as if the developers 
    // are asking for a relationship's value. This covers both types of values. 
    if (array_key_exists($key, $this->attributes) || 
     $this->hasGetMutator($key)) { 
     return $this->getAttributeValue($key); 
    } 

    // Here we will determine if the model base class itself contains this given key 
    // since we do not want to treat any of those methods are relationships since 
    // they are all intended as helper methods and none of these are relations. 
    if (method_exists(self::class, $key)) { 
     return; 
    } 

    return $this->getRelationValue($key); 
} 

、最後の行return $this->getRelationValue($key);を取得するための責任があります関係。ソースコードを読んで、各関数の呼び出しを追跡すると、そのアイデアが得られます。 Illuminate\Database\Eloquent\Model.php::__getメソッドから開始します。 Btw、このコードはLaravelの最新バージョンから取得されますが、最終的にはプロセスは同じです。

要約:Laravel最初のチェックで/ $kayがアクセスされるプロパティは、モデルの特性であるか、モデル自体に定義されたアクセサメソッドの場合、それは単にプロパティがそれ以外の場合は、さらにチェックを維持することを返し、もしあればその名前(プロパティ/ $kay)を使用してモデルで定義されたメソッドが見つかった場合は、単に関係を返します。

関連する問題