1

任何人都可以解釋這種行爲嗎?十月CMS查詢生成器無法獲得關係模型

在例子中,兩種型號:

人民,國家

人屬於關聯國家:

public $belongsTo = [                                               
    'country' => [                                                 
     'Test\TestPlugin\Models\Country',                                           
    ] 

我創建的每個模型的條目,它關聯。

有鼓搗轉儲:

>>> Test\TestPlugin\Models\People::all();                                           
=> October\Rain\Database\Collection {#926                                           
    all: [                                                   
     Test\Testplugin\Models\People {#928                                           
     id: 1,                                                  
     country_id: 1,                                                
     },                                                   
     Test\Testplugin\Models\People {#930                                           
     id: 2,                                                  
     country_id: 0,                                                
     },                                                   
    ],                                                    
    }  

>>> Test\TestPlugin\Models\People::with('country')->get();                                       
=> October\Rain\Database\Collection {#963 
    all: [ 
     Test\Testplugin\Models\People {#943 
     id: 1, 
     country_id: 1, 
     country: Test\Testplugin\Models\Country {#965 
      id: 1, 
      name: "Russia", 
     },                                                   
     },                                                   
     Test\Testplugin\Models\People {#945 
     id: 2, 
     country_id: 0, 
     country: null, 
     },                                                   
    ],                                                    
    }   

我看到人們#1與國家#1的關係,但是當我試圖讓查詢生成器這個關係,空車返回集合:

>>> Test\TestPlugin\Models\People::country()->get();                                        
=> October\Rain\Database\Collection {#970 
    all: [], 
    }                                                    
>>> 

爲什麼?

回答

0

您應該首先獲取人物模型,然後您可以獲取特定模型的國家/地區。

事情是這樣的:

$people = Test\TestPlugin\Models\People::all(); 
foreach ($people as $person){ 
    $country = $person->country; 
    # do something with the country 
} 

PS。 $person->country返回國模型和$person->country()返回查詢生成器對象

+0

我看看爲方法,而不是動態屬性。我的錯誤是我嘗試將方法應用於許多條目。我必須得到一個條目,然後調用方法,如下所示: Test \ TestPlugin \ Models \ People :: find(1) - > country() - > get(); – user2599458

0

而是調用關係法對整個模型,首先需要選擇一個條目:

Test\TestPlugin\Models\People::find(1)->country()->get(); 

然後查詢構建器返回的關係正是爲了這個項目,不是對全部;

0

您可以向人民模型添加protected $with = ['country'];躍躍欲試負載的關係是一樣的$person = People::with('country')->find(1);

然後你就可以訪問的關係作爲屬性$person->country->name也嘗試People::with('country')->get()代替People::country()->get()