Saving Entry with Category field I am stuck on saving entry with a category field.
The error message I get is about not being able to create/update the entry in the relations table.

$accomodationTypecategory = ['title'=&gt;'Hotel']

$entry = new EntryModel();
$entry-&gt;sectionId = 3;
$entry-&gt;typeId = 3;
$entry-&gt;authorId = 1;
$entry-&gt;enabled = true;
$entry-&gt;setContent(
    $entry-&gt;getContent()-&gt;setAttributes([
        'title' =&gt; 'Test Entry', 
        'body' =&gt; "Testing", 
        'address'=&gt;"101 Silver Avenue",
        'phone'=&gt;'0209900292092',
        'websiteAddress'=&gt;'www.example.com',
        'towns'=&gt;'Newy', 
        'accommodationType'=&gt;$accomodationTypecategory
    ]);

craft()-&gt;entries-&gt;saveEntry($entry);


Any help will be appreciated.
To set a related category (or any other kind of element) you will want to pass an array of categoryIds (elementIds) — even if, as in this case, there is only one category or element. You can either set the ID as a static value if it's predefined or dynamically look it up based on the title, slug or any other unique element attribute.

$criteria = craft()-&gt;elements-&gt;getCriteria(ElementType::Category);
$criteria-&gt;title = 'Hotel';
$accomodationTypeCategory = craft()-&gt;elements-&gt;findElements($criteria);

$entry = new EntryModel();
$entry-&gt;sectionId = 3;
$entry-&gt;typeId = 3;
$entry-&gt;authorId = 1;
$entry-&gt;enabled = true;
$entry-&gt;getContent()-&gt;setAttributes(array(
    'title'             =&gt; 'Test Entry', 
    'body'              =&gt; 'Testing', 
    'address'           =&gt; '101 Silver Avenue',
    'phone'             =&gt; '0209900292092',
    'websiteAddress'    =&gt; 'www.example.com',
    'towns'             =&gt; 'Newy', 
    'accommodationType' =&gt; array(
        $accomodationTypeCategory[0]-&gt;id
    )
);
craft()-&gt;entries-&gt;saveEntry($entry);