あなたが定義した関係は、1対1の関係を作ることだけを許します。
意味は、各カテゴリには1つのみの親がありますと親は1つの子のみです。 私はこれがあなたが探している行動ではないと推測しています。ここで
$this->hasOne('category_id', 'Category', 'parent_category_id', ['alias' => 'category_id']);
は1つのカテゴリが複数の子を持つことができます1つの親
と 1親を持つことができる1 Nとの関係の一例です。
混乱を避けるために、関係に意味のある別名を付ける必要があります。
public function initialize()
{
// a category can have multiple child categories
$this->hasMany('category_id', 'Category', 'parent_category_id', ['alias' => 'child_categories']);
// a category only has one parent category
$this->belongsTo('parent_category_id', 'Category', 'category_id', ['alias' => 'parent_category']);
}
を次のようにあなたが上記の関係を使用することができます
// will return an array of Category objects. Because our relation was "hasMany"
$categoryChildren = $category->getRelated('child_categories');
// will return a single Category object. Because we can only have one parent
$categoryParent = $category->getRelated('parent_category');
例(there are also other methods to request related dataことに注意してください):
category_id | parent_category_id | category_name
----------- | ------------------ | -------------
1 | null | A
2 | 1 | B
3 | 1 | C
4 | 2 | D
5 | 4 | E
// returns categories: B, C
$category = Category::findFirstById(1)->getRelated('child_categories');
// returns categories: null
$category = Category::findFirstById(1)->getRelated('parent_category');
// return categories: D
$category = Category::findFirstById(2)->getRelated('child_categories');
// returns categories: A
$category = Category::findFirstById(2)->getRelated('parent_category');
// return categories: null
$category = Category::findFirstById(3)->getRelated('child_categories');
// returns categories: A
$category = Category::findFirstById(3)->getRelated('parent_category');
// return categories: E
$category = Category::findFirstById(4)->getRelated('child_categories');
// returns categories: B
$category = Category::findFirstById(4)->getRelated('parent_category');
// return categories: null
$category = Category::findFirstById(5)->getRelated('child_categories');
// returns categories: D
$category = Category::findFirstById(5)->getRelated('parent_category');
// returns categories: B
$category = Category::findFirstById(5)->getRelated('parent_category')->getRelated('parent_category');
: では、次のデータを考えてみましょう
最後の例で分かるように、一連のカテゴリを作成できます。
残念ながら、この質問は完全に不明です。どのような無限ループが必要ですか?あなたはそれで何をしたいですか?あなたのコードには全くループがありません... – YakovL
@ YakovL、彼は一連のカテゴリの間に連鎖関係を作りたいと考えています。 – Timothy
@ティモシー、あなたは正しいです、私は2日以来試みてきましたが、完了していません – Hanik