如何在symfony2 API中插入带有外键的数据

时间:2015-02-04 13:25:19

标签: symfony doctrine-orm

curl -v -H "Content-Type: application/json" -d "{\"user\":1,\"userapikey\":\"aaaaaaaaaaaaaaaaaa\",\"title\":\"test tile\"}" http://localhost/us/serenify/web/app_dev.php/userapi/create

我正在传递数据,以便为特定用户创建apikey记录。

在上面的表达式中,user是来自用户主表的forign键。

public function processform(ApiKey $apikey,Request $request)
 {  
    $apiuser = new ApiUser();       
    $apiform = $this->createForm(new ApiKeyType(), $apikey);        
    $apiform->submit($request);  

    if($apiform->isValid()) 
    {    
       // $page = $apiform->getData();        
        $content = json_decode($request->getContent());            
        $apikey->setUserApikey($content->userapikey);
        $apikey->setTitle($content->title);

        $em = $this->getDoctrine()->getManager();            

        $em->persist($apikey);
        $em->flush();


        $data=array(
            "success"=>'true',
            "msg"=>'Record inserted!'    
        );
         $response = new Response(json_encode($data));
         $response->setStatusCode(200);
         $response->headers->set('Content-Type', 'application/json');  
    }
    else
    {

        $out=array(
        "success"=>'true',
        "msg"=>'invalid form data!'            
        );              
        $response = new Response(json_encode($out));
        $response->setStatusCode(204);
        $response->headers->set('Content-Type', 'application/json');
    }


    return $response;
  }

这是我的控制器。

class ApiKey
{
 /**
 * @var User 
 * 
 * @ORM\ManyToOne(targetEntity="ApiUser", inversedBy="apikey",cascade={"persist"})
 * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
 */
private $user;

/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var string
 *
 * @ORM\Column(name="userapikey", type="string", length=255)
 */
private $userapikey;

/**
 * @var string
 *
 * @ORM\Column(name="title", type="string", length=255)
 */
private $title;


/**
 * Get id
 *
 * @return integer 
 */
public function getId()
{
    return $this->id;
}

/**
 * Set apikey
 *
 * @param string $userapikey
 * @return userapi
 */
public function setUserApikey($userapikey)
{
    $this->userapikey = $userapikey;

    return $this;
}

/**
 * Get apikey
 *
 * @return string 
 */
public function getUserApikey()
{
    return $this->userapikey;
}

/**
 * Set title
 *
 * @param string $title
 * @return userapi
 */
public function setTitle($title)
{
    $this->title = $title;

    return $this;
}

/**
 * Get title
 *
 * @return string 
 */
public function getTitle()
{
    return $this->title;
}

/**
 * Get user
 *
 * @return integer 
 */
public function getUser()
{
    return $this->user;
}
 /**
 * Set User
 *
 * @param integer $user
 * @return userapi
 */
public function setUser(ApiUser $value = null)
{
    $this->user = $value;        
    return $this;
}
}

班级ApiUser

class ApiUser
{

 /**
 * @var ArrayCollection
 * 
 * @ORM\OneToMany(targetEntity="ApiKey", mappedBy="apiuser")
 */
 private $apikeys;
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var string
 *
 * @ORM\Column(name="username", type="string", length=255)
 * @Assert\NotBlank()
 */
private $username;

/**
 * @var string
 * @Assert\NotBlank()
 *
 * @ORM\Column(name="userpassword", type="string", length=255)
 */
private $userpassword;

/**
 * Get id
 *
 * @return integer 
 */
public function getId()
{
    return $this->id;
}

/**
 * Set username
 *
 * @param string $username
 * @return user
 */
public function setUsername($username)
{
    $this->username = $username;

    return $this;
}

/**
 * Get username
 *
 * @return string 
 */
public function getUsername()
{
    return $this->username;
}

/**
 * Set userpassword
 *
 * @param string $userpassword
 * @return user
 */
public function setUserpassword($userpassword)
{
    $this->userpassword = $userpassword;

    return $this;
}
/**
 * Get userpassword
 *
 * @return string 
 */
public function getUserpassword()
{
    return $this->userpassword;
}


}

&安培;这是实体类。

请帮助插入记录,此时NULL值将插入到userid列中。

1 个答案:

答案 0 :(得分:0)

您需要DataTransformerhttp://symfony.com/doc/current/cookbook/form/data_transformers.html

class UserToIdTransformer implements DataTransformerInterface
{
/**
 * @var ObjectManager
 */
private $om;

/**
 * @param ObjectManager $om
 */
public function __construct(ObjectManager $om)
{
    $this->om = $om;
}

/**
 * Transforms an object (user) to an int (id).
 *
 * @param  User|null $user
 * @return integer
 */
public function transform($user)
{
    if (null === $user) {
        return "";
    }

    return $user->getId();
}

/**
 * Transforms an integer (id) to an object (User).
 *
 * @param  integer $number
 *
 * @return User|null
 *
 * @throws TransformationFailedException if object (user) is not found.
 */
public function reverseTransform($id)
{
    if (!$id) {
        return null;
    }

    $user = $this->om
        ->getRepository('YourBundle:User')
        ->find($id);

    if (null === $user) {
        throw new TransformationFailedException(sprintf(
            'An user with id "%s" does not exist!',
            $id
        ));
    }

    return $user;
}
}

然后在你的formtype中添加字段:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    // ...

    // this assumes that the entity manager was passed in as an option
    $entityManager = $options['em'];
    $transformer = new UserToIdTransformer($entityManager);
       // add a normal text field, but add your transformer to it
    $builder->add(
        $builder->create('user', 'text')
            ->addModelTransformer($transformer)
    ); 

请注意,通过一些更改,您可以通过提供用户名而不是ID来使其工作。