douzhe2981
2016-06-28 00:00
浏览 49
已采纳

在SilverStripe中获取has_one关系

I have a DataObject called Applicant and it $has_one Member (this is the SilverStripe Member class).

private static $has_one = array (
    'MemberApplicant' => 'Member'
);

When a member is logged in and visits the ApplicationPage I want to be able to populate the form based on the members Applicant data.

I can make this work but I feel like I should be able to access the data easier.

Here is what I do:

$memberID = Member::currentUserID();
$applicant = Applicant::get()->filter('MemberApplicantID', $memberID)->first();

$form->loadDataFrom($applicant);

Shouldn't I be able to instantiate a Member and then call its relative $MemberApplicant?

图片转代码服务由CSDN问答提供 功能建议

我有一个 DataObject ,名为 Applicant ,它是 $ has_one Member (这是SilverStripe Member 类)。

  private static $ has_one = 数组(
'MemberApplicant'=>'成员'
); 
   
 
 

当会员登录并访问 ApplicationPage 我希望能够根据成员 Applicant 数据填充表单。

我可以使这项工作,但我觉得我应该能够访问 数据更容易。

以下是我的工作:

  $ memberID = Member :: currentUserID(); 
 $ applicant = Applicant :: get  () - >过滤器('MemberApplicantID',$ memberID) - > first(); 
 
 $ form-> loadDataFrom($ applicant); 
   
 
  

我不应该能够实例化 Member 然后调用它的相对 $ MemberApplicant

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

  • dsjlqkbpn029473708 2016-06-28 06:52
    最佳回答

    Shouldn't I be able to instantiate a Member and then call its relative $MemberApplicant?

    Of course. I assume you have a 1:1 relation, then you have to define the counter part on Member using $belongs_to (see this diagram)

    class Applicant extends DataObject
    {
    private static $has_one = [
        'MemberApplicant' => 'Member'
    ];
    ...
    
    class MemberApplicantExtenension extends DataExtension
    {
    private static $belongs_to = [
        'Applicant' => 'Applicant'
    ];
    
    ...
    

    Now add the DataExtension to the Member object in /mysite/_config/config.yml

    Member:
      extensions:
        - MemberApplicantExtenension
    

    and run a dev/build?flush.

    Now you're able to get the related Applicant from the Member using built in ORM magic:

    //Get the current Member
    $member = Member::CurrentUser();
    
    //get the $belongs_to
    $applicant = $member->Applicant();
    
    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题