2

在 Rails 中,比如说一个博客应用程序,给定一个特定的帖子对象,你可以得到帖子作者的名字,如下所示:

post = Post.find(1)    
author_name = post.author.name

是否有使用 DataObject 的 PHP 等价物,例如(在这里只是虚构的语法):

$postsTable = DB_DataObject::factory('posts');
$authorName = (($postsTable->id = 1)->find(true))->author->name;

              |  finds and autofetches post #1  |->author->name
4

2 回答 2

1

如果你想要一个带有类似 API 的 ORM,我会推荐PHP ActiveRecord

$posts = Post::find('all', array('limit' => 10, 'include' => array('author')));
foreach ($posts as $post) {
   echo $post->author->first_name;
}

http://www.phpactiverecord.org/projects/main/wiki/Finders


您可能还对Propel ORM感兴趣:

$book = BookQuery::create()
  ->useAuthorQuery()
    ->filterByFirstName('Leo')
  ->endUse()
  ->with('Author')
  ->findOne();
$author = $book->getAuthor();

http://www.propelorm.org/wiki/Documentation/1.6/Relationships

于 2011-06-03T16:42:35.230 回答
0

DB_DataObject 没有流畅的接口,因此您无法链接。但是你可以这样做:

$postsTable = DB_DataObject::factory('posts');
if($postsTable->get($id)) {
  $authorname = $postsTable->getLink('author_id')->name;
}
于 2011-07-01T07:53:52.320 回答