假设我有 3 个模型,一个、两个和三个。
模型一有很多三,模型二有很多三,三个属于一和二。
模型:
class Model_One extends ORM {
protected $_primary_key = 'one_id';
protected $_has_many = array(
'threes'=> array(
'model' => 'three',
'through' => 'ones_threes',
'far_key' => 'three_id',
'foreign_key' => 'one_id'
),
);
}
class Model_Two extends ORM {
protected $_primary_key = 'two_id';
protected $_has_many = array(
'threes'=> array(
'model' => 'three',
'through' => 'twos_threes',
'far_key' => 'three_id',
'foreign_key' => 'two_id'
),
);
}
class Model_Three extends ORM {
protected $_primary_key = 'three_id';
protected $_belongs_to = array(
'ones'=> array(
'model' => 'one',
'through' => 'ones_threes',
'far_key' => 'one_id',
'foreign_key' => 'three_id'
),
'twos'=> array(
'model' => 'two',
'through' => 'twos_threes',
'far_key' => 'two_id',
'foreign_key' => 'three_id'
),
);
}
我显示一,二,三。
$getTwos=ORM::factory('two')->find_all();
foreach($getTwos as $getTwo)
{
echo $getTwo->two_category_title;
foreach($getTwo->three->find_all() as $getThree)
{
echo $getThree->three_title;
echo $getThree->one->one_author;
}
}
假设我有作者 A 和 B 以及标题 1、标题 2、标题 3 和标题 4。A 具有标题 1、2、3,B 具有标题 4。
问题是回显$getThree->一>one_author;将回显 A, B, NULL, NULL。
如何正确回显信息?
模型Three
中的关系定义不正确。似乎One
拥有并属于许多Threes
(HABTM或"具有许多通过"),Two
模型也是如此。以下是您需要的:
class Model_Three extends ORM {
protected $_primary_key = 'three_id';
protected $_has_many = array(
'ones'=> array(
'model' => 'one',
'through' => 'ones_threes',
'far_key' => 'one_id',
'foreign_key' => 'three_id'
),
'twos'=> array(
'model' => 'two',
'through' => 'twos_threes',
'far_key' => 'two_id',
'foreign_key' => 'three_id'
),
);
}
PS. foreign_key
是可选的,因为您已经在$_primary_key
属性中定义了它。
缴费灵。下面是"帖子仅属于一个用户"关系的示例:
class Model_User extends ORM {
protected $_has_many = array(
'posts' => array(),
);
}
class Model_Post extends ORM {
protected $_belongs_to = array(
'author' => array(
'model' => 'user',
// ignore if you have a `author_id` foreign key
'foreign_key' => 'user_id',
),
);
protected $_has_many = array(...);
}
// usage
$post = ORM::factory('post', 1);
echo $post->author->username;
$post->author = ORM::factory('user', 1);
$user = ORM::factory('user', 1);
foreach($user->posts->where('published', '=', 1)->find_all() as $posts) {
echo $post->title;
}