Update a field in database via modelHow to call a model method from controller in Magento2How to add date filed in admin & show on front in magento2I created a custom module ,but getting error, not able to figure out what the error is about. How to get out of this error?Magento 2: How to override newsletter Subscriber modelMagento 2.1 Create a filter in the product grid by new attributeMagento 2.1.6 Cannot save shipmentI have created an extension to show Customer Company Name in Order grid. But when creating new order, order is not showing in order gridNot able to add/update magento2 category post upgrade from 1.9 to 2.1.0Magento 2 Create dynamic array From different Model Collection to use in multi select in gridMagento 2.3 Can't view module's front end page output?

Accidentally leaked the solution to an assignment, what to do now? (I'm the prof)

How did the USSR manage to innovate in an environment characterized by government censorship and high bureaucracy?

How to report a triplet of septets in NMR tabulation?

A Journey Through Space and Time

If I cast Expeditious Retreat, can I Dash as a bonus action on the same turn?

How old can references or sources in a thesis be?

How to re-create Edward Weson's Pepper No. 30?

declaring a variable twice in IIFE

How to add power-LED to my small amplifier?

What typically incentivizes a professor to change jobs to a lower ranking university?

Shell script not opening as desktop application

DOS, create pipe for stdin/stdout of command.com(or 4dos.com) in C or Batch?

How to make payment on the internet without leaving a money trail?

How is the claim "I am in New York only if I am in America" the same as "If I am in New York, then I am in America?

Japan - Plan around max visa duration

Why Is Death Allowed In the Matrix?

Can I interfere when another PC is about to be attacked?

A newer friend of my brother's gave him a load of baseball cards that are supposedly extremely valuable. Is this a scam?

Why are 150k or 200k jobs considered good when there are 300k+ births a month?

Can a German sentence have two subjects?

How does one intimidate enemies without having the capacity for violence?

Why can't I see bouncing of a switch on an oscilloscope?

Do any Labour MPs support no-deal?

How do I create uniquely male characters?



Update a field in database via model


How to call a model method from controller in Magento2How to add date filed in admin & show on front in magento2I created a custom module ,but getting error, not able to figure out what the error is about. How to get out of this error?Magento 2: How to override newsletter Subscriber modelMagento 2.1 Create a filter in the product grid by new attributeMagento 2.1.6 Cannot save shipmentI have created an extension to show Customer Company Name in Order grid. But when creating new order, order is not showing in order gridNot able to add/update magento2 category post upgrade from 1.9 to 2.1.0Magento 2 Create dynamic array From different Model Collection to use in multi select in gridMagento 2.3 Can't view module's front end page output?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I'm trying to update a field in the database via my database model. All tutorials online about CRUD models seem to just show how to 'CR' and not showing examples of the 'UD'. My code so far:



namespace CompanyNameAdminMenuControllerAdminhtmlHomepageBanner;

class UpdatePosition extends MagentoFrameworkAppActionAction

protected $_postFactory;
protected $_httpRequest;
protected $_postResource;

public function __construct(
MagentoFrameworkAppActionContext $context,
MagentoFrameworkAppRequestHttp $httpRequest,
CompanyNameAdminMenuModelPostFactory $postFactory,
CompanyNameAdminMenuResourceModelPost $postResource
)

$this->_postFactory = $postFactory;
$this->_postResource = $postResource;
$this->_httpRequest = $httpRequest;
return parent::__construct($context);


public function execute()

$post = $this->$postFactory->create();

$post->load(2, 'slide_position')->setId(22)->save();

//$this->getConnection()->update('admincontentbanners_homepageslider_post', ['slide_position' => $data], ["slide_id = ?" => $slideID]);





Any advise would be appreciated..










share|improve this question






















  • Use repository instead of model and cms module is good example of CRUD.

    – Sohel Rana
    Jun 3 '18 at 18:38











  • I didn't know about repositories.. Ill look into using those now.. Man, Magneto moves fast!

    – Bossman
    Jun 3 '18 at 19:06

















0















I'm trying to update a field in the database via my database model. All tutorials online about CRUD models seem to just show how to 'CR' and not showing examples of the 'UD'. My code so far:



namespace CompanyNameAdminMenuControllerAdminhtmlHomepageBanner;

class UpdatePosition extends MagentoFrameworkAppActionAction

protected $_postFactory;
protected $_httpRequest;
protected $_postResource;

public function __construct(
MagentoFrameworkAppActionContext $context,
MagentoFrameworkAppRequestHttp $httpRequest,
CompanyNameAdminMenuModelPostFactory $postFactory,
CompanyNameAdminMenuResourceModelPost $postResource
)

$this->_postFactory = $postFactory;
$this->_postResource = $postResource;
$this->_httpRequest = $httpRequest;
return parent::__construct($context);


public function execute()

$post = $this->$postFactory->create();

$post->load(2, 'slide_position')->setId(22)->save();

//$this->getConnection()->update('admincontentbanners_homepageslider_post', ['slide_position' => $data], ["slide_id = ?" => $slideID]);





Any advise would be appreciated..










share|improve this question






















  • Use repository instead of model and cms module is good example of CRUD.

    – Sohel Rana
    Jun 3 '18 at 18:38











  • I didn't know about repositories.. Ill look into using those now.. Man, Magneto moves fast!

    – Bossman
    Jun 3 '18 at 19:06













0












0








0








I'm trying to update a field in the database via my database model. All tutorials online about CRUD models seem to just show how to 'CR' and not showing examples of the 'UD'. My code so far:



namespace CompanyNameAdminMenuControllerAdminhtmlHomepageBanner;

class UpdatePosition extends MagentoFrameworkAppActionAction

protected $_postFactory;
protected $_httpRequest;
protected $_postResource;

public function __construct(
MagentoFrameworkAppActionContext $context,
MagentoFrameworkAppRequestHttp $httpRequest,
CompanyNameAdminMenuModelPostFactory $postFactory,
CompanyNameAdminMenuResourceModelPost $postResource
)

$this->_postFactory = $postFactory;
$this->_postResource = $postResource;
$this->_httpRequest = $httpRequest;
return parent::__construct($context);


public function execute()

$post = $this->$postFactory->create();

$post->load(2, 'slide_position')->setId(22)->save();

//$this->getConnection()->update('admincontentbanners_homepageslider_post', ['slide_position' => $data], ["slide_id = ?" => $slideID]);





Any advise would be appreciated..










share|improve this question














I'm trying to update a field in the database via my database model. All tutorials online about CRUD models seem to just show how to 'CR' and not showing examples of the 'UD'. My code so far:



namespace CompanyNameAdminMenuControllerAdminhtmlHomepageBanner;

class UpdatePosition extends MagentoFrameworkAppActionAction

protected $_postFactory;
protected $_httpRequest;
protected $_postResource;

public function __construct(
MagentoFrameworkAppActionContext $context,
MagentoFrameworkAppRequestHttp $httpRequest,
CompanyNameAdminMenuModelPostFactory $postFactory,
CompanyNameAdminMenuResourceModelPost $postResource
)

$this->_postFactory = $postFactory;
$this->_postResource = $postResource;
$this->_httpRequest = $httpRequest;
return parent::__construct($context);


public function execute()

$post = $this->$postFactory->create();

$post->load(2, 'slide_position')->setId(22)->save();

//$this->getConnection()->update('admincontentbanners_homepageslider_post', ['slide_position' => $data], ["slide_id = ?" => $slideID]);





Any advise would be appreciated..







magento2 php database






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jun 3 '18 at 18:01









BossmanBossman

34




34












  • Use repository instead of model and cms module is good example of CRUD.

    – Sohel Rana
    Jun 3 '18 at 18:38











  • I didn't know about repositories.. Ill look into using those now.. Man, Magneto moves fast!

    – Bossman
    Jun 3 '18 at 19:06

















  • Use repository instead of model and cms module is good example of CRUD.

    – Sohel Rana
    Jun 3 '18 at 18:38











  • I didn't know about repositories.. Ill look into using those now.. Man, Magneto moves fast!

    – Bossman
    Jun 3 '18 at 19:06
















Use repository instead of model and cms module is good example of CRUD.

– Sohel Rana
Jun 3 '18 at 18:38





Use repository instead of model and cms module is good example of CRUD.

– Sohel Rana
Jun 3 '18 at 18:38













I didn't know about repositories.. Ill look into using those now.. Man, Magneto moves fast!

– Bossman
Jun 3 '18 at 19:06





I didn't know about repositories.. Ill look into using those now.. Man, Magneto moves fast!

– Bossman
Jun 3 '18 at 19:06










2 Answers
2






active

oldest

votes


















0














This loads the specified model , which you want update .



public function execute()

$post = $this->$postFactory->create();
$id_post_update = 19; //Example

$postUpdate = $post->load($id_post_update);
$postUpdate->setSlidePosition(2);
$postUpdate->setId(22);
$postUpdate->save();






share|improve this answer

























  • I'm going to look into repositories now but is "$id_post_update" the primary table ID field? "setSlidePosition()" is that a generated function?

    – Bossman
    Jun 3 '18 at 19:08











  • $id_post_update - this id entity post, which you want update ;"setSlidePosition()" - this magic method , which update 'slide_position'

    – Evgeniy Kapelko
    Jun 3 '18 at 19:17












  • Thanks for your help, i managed to get it working with your code, i didn't need the "$postUpdate->setId(22);"

    – Bossman
    Jun 4 '18 at 20:02











  • Sorry , I get this "->setId(22)" from your example .

    – Evgeniy Kapelko
    Jun 4 '18 at 20:13












  • Yes, that was just me not understanding fully :)

    – Bossman
    Jun 4 '18 at 21:17


















0














Evgeniy Kapelko approach works, but deprecated from Magento 2.1(with certain version I might be mistaken).

Below infromation from class, that was used in Evgeniy Kapelko approach, confirm info about deprecation vendor/magento/framework/Model/AbstractModel.php



/**
* Save object data
*
* @return $this
* @throws Exception
*
* @deprecated 100.1.0 because entities must not be responsible for their own persistence.
* Service contracts should persist entities. Use resource model "save" to implement
* service contract persistence operations.
*/
public function save()

$this->_getResource()->save($this);
return $this;




How correct to work with you model?

We need to use it like described in official documentation.



It can be little bit hard at the begging, but future code will be simple and clear.



In code below, we are going to update Shop entity name.

1) Create interface for you repository, with functions getById and save



<?php

namespace VendorModuleApi;

use VendorModuleApiDataShopInterface;

/**
* Interface SampleInterface
*
* @package AcademyDatabaseApiData
*/
interface ShopRepositoryInterface


/**
* @param VendorModuleApiDataShopInterface $shopList
*
* @return mixed
*/
public function save(ShopInterface $shopList);

/**
* @param int $id
*
* @return mixed
*/
public function getById(int $id);



2) Implement interface in you repository and define functions



<?php

namespace VendorModuleModel;


use VendorModuleApiDataShopInterface;
use VendorModuleApiShopRepositoryInterface;
use VendorModuleModelResourceModelShop as ShopResource;
use MagentoFrameworkExceptionAlreadyExistsException;

class ShopRepository implements ShopRepositoryInterface


/**
* @var ShopFactory
*/
private $shopList;
/**
* @var Shop
*/
private $shopListResource;

public function __construct(
ShopFactory $shopList,
ShopResource $shopListResource
)
$this->shopList = $shopList;
$this->shopListResource = $shopListResource;


/**
* @param ShopInterface $shop
*
* @return void
*
* @throws AlreadyExistsException
* @throws Exception
*/
public function save(ShopInterface $shop)

try
$this->shopListResource->save($shop);
catch (AlreadyExistsException $e)
//catch exception
catch (Exception $e)
//catch exception



/**
* @param int $shopId
*
* @return VendorModuleModelShop
*/
public function getById(int $shopId)

$shopListModel = $this->shopList->create();
$this->shopListResource->load($shopListModel, $shopId);

return $shopListModel;




3) Add Repository and RepositoryInterface to di.xml



<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="VendorModuleApiShopRepositoryInterface"
type="VendorModuleModelShopRepository"/>
</config>


4) Start using it (i'm using it in controller)



 /**
* @param ShopInterfaceFactory $shopListFactory
* @param ShopRepositoryInterface $shopListRepository
*/
public function __construct(
VendorModuleApiDataShopInterfaceFactory $shopListFactory,
VendorModuleApiShopRepositoryInterface $shopListRepository
)
$this->shopListFactory = $shopListFactory;
$this->shopListRepository = $shopListRepository;


public function execute()

$shopId = 1;//use needed entity ID

/**
* Create entity
*
* @var Shop $shopList
*/
$shopList = $this->shopListFactory->create();
$shopList->setData(['name' => 'shop name']);
$this->shopListRepository->save($shopList);

/**
* Read entity
*
* @var Shop $shopList
*/
$shopList = $this->shopListRepository->getById($shopId);
$shopData = $shopList->getData();//data of entity

/**
* Update entity
*
* @var Shop $shopList
*/
$shopList = $this->shopListRepository->getById($shopId);
$shopList->addData(['name' => 'bdn']);
$this->shopListRepository->save($shopList);






share|improve this answer

























    Your Answer








    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "479"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f228465%2fupdate-a-field-in-database-via-model%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    This loads the specified model , which you want update .



    public function execute()

    $post = $this->$postFactory->create();
    $id_post_update = 19; //Example

    $postUpdate = $post->load($id_post_update);
    $postUpdate->setSlidePosition(2);
    $postUpdate->setId(22);
    $postUpdate->save();






    share|improve this answer

























    • I'm going to look into repositories now but is "$id_post_update" the primary table ID field? "setSlidePosition()" is that a generated function?

      – Bossman
      Jun 3 '18 at 19:08











    • $id_post_update - this id entity post, which you want update ;"setSlidePosition()" - this magic method , which update 'slide_position'

      – Evgeniy Kapelko
      Jun 3 '18 at 19:17












    • Thanks for your help, i managed to get it working with your code, i didn't need the "$postUpdate->setId(22);"

      – Bossman
      Jun 4 '18 at 20:02











    • Sorry , I get this "->setId(22)" from your example .

      – Evgeniy Kapelko
      Jun 4 '18 at 20:13












    • Yes, that was just me not understanding fully :)

      – Bossman
      Jun 4 '18 at 21:17















    0














    This loads the specified model , which you want update .



    public function execute()

    $post = $this->$postFactory->create();
    $id_post_update = 19; //Example

    $postUpdate = $post->load($id_post_update);
    $postUpdate->setSlidePosition(2);
    $postUpdate->setId(22);
    $postUpdate->save();






    share|improve this answer

























    • I'm going to look into repositories now but is "$id_post_update" the primary table ID field? "setSlidePosition()" is that a generated function?

      – Bossman
      Jun 3 '18 at 19:08











    • $id_post_update - this id entity post, which you want update ;"setSlidePosition()" - this magic method , which update 'slide_position'

      – Evgeniy Kapelko
      Jun 3 '18 at 19:17












    • Thanks for your help, i managed to get it working with your code, i didn't need the "$postUpdate->setId(22);"

      – Bossman
      Jun 4 '18 at 20:02











    • Sorry , I get this "->setId(22)" from your example .

      – Evgeniy Kapelko
      Jun 4 '18 at 20:13












    • Yes, that was just me not understanding fully :)

      – Bossman
      Jun 4 '18 at 21:17













    0












    0








    0







    This loads the specified model , which you want update .



    public function execute()

    $post = $this->$postFactory->create();
    $id_post_update = 19; //Example

    $postUpdate = $post->load($id_post_update);
    $postUpdate->setSlidePosition(2);
    $postUpdate->setId(22);
    $postUpdate->save();






    share|improve this answer















    This loads the specified model , which you want update .



    public function execute()

    $post = $this->$postFactory->create();
    $id_post_update = 19; //Example

    $postUpdate = $post->load($id_post_update);
    $postUpdate->setSlidePosition(2);
    $postUpdate->setId(22);
    $postUpdate->save();







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Jun 3 '18 at 18:40

























    answered Jun 3 '18 at 18:35









    Evgeniy KapelkoEvgeniy Kapelko

    1,1661317




    1,1661317












    • I'm going to look into repositories now but is "$id_post_update" the primary table ID field? "setSlidePosition()" is that a generated function?

      – Bossman
      Jun 3 '18 at 19:08











    • $id_post_update - this id entity post, which you want update ;"setSlidePosition()" - this magic method , which update 'slide_position'

      – Evgeniy Kapelko
      Jun 3 '18 at 19:17












    • Thanks for your help, i managed to get it working with your code, i didn't need the "$postUpdate->setId(22);"

      – Bossman
      Jun 4 '18 at 20:02











    • Sorry , I get this "->setId(22)" from your example .

      – Evgeniy Kapelko
      Jun 4 '18 at 20:13












    • Yes, that was just me not understanding fully :)

      – Bossman
      Jun 4 '18 at 21:17

















    • I'm going to look into repositories now but is "$id_post_update" the primary table ID field? "setSlidePosition()" is that a generated function?

      – Bossman
      Jun 3 '18 at 19:08











    • $id_post_update - this id entity post, which you want update ;"setSlidePosition()" - this magic method , which update 'slide_position'

      – Evgeniy Kapelko
      Jun 3 '18 at 19:17












    • Thanks for your help, i managed to get it working with your code, i didn't need the "$postUpdate->setId(22);"

      – Bossman
      Jun 4 '18 at 20:02











    • Sorry , I get this "->setId(22)" from your example .

      – Evgeniy Kapelko
      Jun 4 '18 at 20:13












    • Yes, that was just me not understanding fully :)

      – Bossman
      Jun 4 '18 at 21:17
















    I'm going to look into repositories now but is "$id_post_update" the primary table ID field? "setSlidePosition()" is that a generated function?

    – Bossman
    Jun 3 '18 at 19:08





    I'm going to look into repositories now but is "$id_post_update" the primary table ID field? "setSlidePosition()" is that a generated function?

    – Bossman
    Jun 3 '18 at 19:08













    $id_post_update - this id entity post, which you want update ;"setSlidePosition()" - this magic method , which update 'slide_position'

    – Evgeniy Kapelko
    Jun 3 '18 at 19:17






    $id_post_update - this id entity post, which you want update ;"setSlidePosition()" - this magic method , which update 'slide_position'

    – Evgeniy Kapelko
    Jun 3 '18 at 19:17














    Thanks for your help, i managed to get it working with your code, i didn't need the "$postUpdate->setId(22);"

    – Bossman
    Jun 4 '18 at 20:02





    Thanks for your help, i managed to get it working with your code, i didn't need the "$postUpdate->setId(22);"

    – Bossman
    Jun 4 '18 at 20:02













    Sorry , I get this "->setId(22)" from your example .

    – Evgeniy Kapelko
    Jun 4 '18 at 20:13






    Sorry , I get this "->setId(22)" from your example .

    – Evgeniy Kapelko
    Jun 4 '18 at 20:13














    Yes, that was just me not understanding fully :)

    – Bossman
    Jun 4 '18 at 21:17





    Yes, that was just me not understanding fully :)

    – Bossman
    Jun 4 '18 at 21:17













    0














    Evgeniy Kapelko approach works, but deprecated from Magento 2.1(with certain version I might be mistaken).

    Below infromation from class, that was used in Evgeniy Kapelko approach, confirm info about deprecation vendor/magento/framework/Model/AbstractModel.php



    /**
    * Save object data
    *
    * @return $this
    * @throws Exception
    *
    * @deprecated 100.1.0 because entities must not be responsible for their own persistence.
    * Service contracts should persist entities. Use resource model "save" to implement
    * service contract persistence operations.
    */
    public function save()

    $this->_getResource()->save($this);
    return $this;




    How correct to work with you model?

    We need to use it like described in official documentation.



    It can be little bit hard at the begging, but future code will be simple and clear.



    In code below, we are going to update Shop entity name.

    1) Create interface for you repository, with functions getById and save



    <?php

    namespace VendorModuleApi;

    use VendorModuleApiDataShopInterface;

    /**
    * Interface SampleInterface
    *
    * @package AcademyDatabaseApiData
    */
    interface ShopRepositoryInterface


    /**
    * @param VendorModuleApiDataShopInterface $shopList
    *
    * @return mixed
    */
    public function save(ShopInterface $shopList);

    /**
    * @param int $id
    *
    * @return mixed
    */
    public function getById(int $id);



    2) Implement interface in you repository and define functions



    <?php

    namespace VendorModuleModel;


    use VendorModuleApiDataShopInterface;
    use VendorModuleApiShopRepositoryInterface;
    use VendorModuleModelResourceModelShop as ShopResource;
    use MagentoFrameworkExceptionAlreadyExistsException;

    class ShopRepository implements ShopRepositoryInterface


    /**
    * @var ShopFactory
    */
    private $shopList;
    /**
    * @var Shop
    */
    private $shopListResource;

    public function __construct(
    ShopFactory $shopList,
    ShopResource $shopListResource
    )
    $this->shopList = $shopList;
    $this->shopListResource = $shopListResource;


    /**
    * @param ShopInterface $shop
    *
    * @return void
    *
    * @throws AlreadyExistsException
    * @throws Exception
    */
    public function save(ShopInterface $shop)

    try
    $this->shopListResource->save($shop);
    catch (AlreadyExistsException $e)
    //catch exception
    catch (Exception $e)
    //catch exception



    /**
    * @param int $shopId
    *
    * @return VendorModuleModelShop
    */
    public function getById(int $shopId)

    $shopListModel = $this->shopList->create();
    $this->shopListResource->load($shopListModel, $shopId);

    return $shopListModel;




    3) Add Repository and RepositoryInterface to di.xml



    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="VendorModuleApiShopRepositoryInterface"
    type="VendorModuleModelShopRepository"/>
    </config>


    4) Start using it (i'm using it in controller)



     /**
    * @param ShopInterfaceFactory $shopListFactory
    * @param ShopRepositoryInterface $shopListRepository
    */
    public function __construct(
    VendorModuleApiDataShopInterfaceFactory $shopListFactory,
    VendorModuleApiShopRepositoryInterface $shopListRepository
    )
    $this->shopListFactory = $shopListFactory;
    $this->shopListRepository = $shopListRepository;


    public function execute()

    $shopId = 1;//use needed entity ID

    /**
    * Create entity
    *
    * @var Shop $shopList
    */
    $shopList = $this->shopListFactory->create();
    $shopList->setData(['name' => 'shop name']);
    $this->shopListRepository->save($shopList);

    /**
    * Read entity
    *
    * @var Shop $shopList
    */
    $shopList = $this->shopListRepository->getById($shopId);
    $shopData = $shopList->getData();//data of entity

    /**
    * Update entity
    *
    * @var Shop $shopList
    */
    $shopList = $this->shopListRepository->getById($shopId);
    $shopList->addData(['name' => 'bdn']);
    $this->shopListRepository->save($shopList);






    share|improve this answer





























      0














      Evgeniy Kapelko approach works, but deprecated from Magento 2.1(with certain version I might be mistaken).

      Below infromation from class, that was used in Evgeniy Kapelko approach, confirm info about deprecation vendor/magento/framework/Model/AbstractModel.php



      /**
      * Save object data
      *
      * @return $this
      * @throws Exception
      *
      * @deprecated 100.1.0 because entities must not be responsible for their own persistence.
      * Service contracts should persist entities. Use resource model "save" to implement
      * service contract persistence operations.
      */
      public function save()

      $this->_getResource()->save($this);
      return $this;




      How correct to work with you model?

      We need to use it like described in official documentation.



      It can be little bit hard at the begging, but future code will be simple and clear.



      In code below, we are going to update Shop entity name.

      1) Create interface for you repository, with functions getById and save



      <?php

      namespace VendorModuleApi;

      use VendorModuleApiDataShopInterface;

      /**
      * Interface SampleInterface
      *
      * @package AcademyDatabaseApiData
      */
      interface ShopRepositoryInterface


      /**
      * @param VendorModuleApiDataShopInterface $shopList
      *
      * @return mixed
      */
      public function save(ShopInterface $shopList);

      /**
      * @param int $id
      *
      * @return mixed
      */
      public function getById(int $id);



      2) Implement interface in you repository and define functions



      <?php

      namespace VendorModuleModel;


      use VendorModuleApiDataShopInterface;
      use VendorModuleApiShopRepositoryInterface;
      use VendorModuleModelResourceModelShop as ShopResource;
      use MagentoFrameworkExceptionAlreadyExistsException;

      class ShopRepository implements ShopRepositoryInterface


      /**
      * @var ShopFactory
      */
      private $shopList;
      /**
      * @var Shop
      */
      private $shopListResource;

      public function __construct(
      ShopFactory $shopList,
      ShopResource $shopListResource
      )
      $this->shopList = $shopList;
      $this->shopListResource = $shopListResource;


      /**
      * @param ShopInterface $shop
      *
      * @return void
      *
      * @throws AlreadyExistsException
      * @throws Exception
      */
      public function save(ShopInterface $shop)

      try
      $this->shopListResource->save($shop);
      catch (AlreadyExistsException $e)
      //catch exception
      catch (Exception $e)
      //catch exception



      /**
      * @param int $shopId
      *
      * @return VendorModuleModelShop
      */
      public function getById(int $shopId)

      $shopListModel = $this->shopList->create();
      $this->shopListResource->load($shopListModel, $shopId);

      return $shopListModel;




      3) Add Repository and RepositoryInterface to di.xml



      <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
      <preference for="VendorModuleApiShopRepositoryInterface"
      type="VendorModuleModelShopRepository"/>
      </config>


      4) Start using it (i'm using it in controller)



       /**
      * @param ShopInterfaceFactory $shopListFactory
      * @param ShopRepositoryInterface $shopListRepository
      */
      public function __construct(
      VendorModuleApiDataShopInterfaceFactory $shopListFactory,
      VendorModuleApiShopRepositoryInterface $shopListRepository
      )
      $this->shopListFactory = $shopListFactory;
      $this->shopListRepository = $shopListRepository;


      public function execute()

      $shopId = 1;//use needed entity ID

      /**
      * Create entity
      *
      * @var Shop $shopList
      */
      $shopList = $this->shopListFactory->create();
      $shopList->setData(['name' => 'shop name']);
      $this->shopListRepository->save($shopList);

      /**
      * Read entity
      *
      * @var Shop $shopList
      */
      $shopList = $this->shopListRepository->getById($shopId);
      $shopData = $shopList->getData();//data of entity

      /**
      * Update entity
      *
      * @var Shop $shopList
      */
      $shopList = $this->shopListRepository->getById($shopId);
      $shopList->addData(['name' => 'bdn']);
      $this->shopListRepository->save($shopList);






      share|improve this answer



























        0












        0








        0







        Evgeniy Kapelko approach works, but deprecated from Magento 2.1(with certain version I might be mistaken).

        Below infromation from class, that was used in Evgeniy Kapelko approach, confirm info about deprecation vendor/magento/framework/Model/AbstractModel.php



        /**
        * Save object data
        *
        * @return $this
        * @throws Exception
        *
        * @deprecated 100.1.0 because entities must not be responsible for their own persistence.
        * Service contracts should persist entities. Use resource model "save" to implement
        * service contract persistence operations.
        */
        public function save()

        $this->_getResource()->save($this);
        return $this;




        How correct to work with you model?

        We need to use it like described in official documentation.



        It can be little bit hard at the begging, but future code will be simple and clear.



        In code below, we are going to update Shop entity name.

        1) Create interface for you repository, with functions getById and save



        <?php

        namespace VendorModuleApi;

        use VendorModuleApiDataShopInterface;

        /**
        * Interface SampleInterface
        *
        * @package AcademyDatabaseApiData
        */
        interface ShopRepositoryInterface


        /**
        * @param VendorModuleApiDataShopInterface $shopList
        *
        * @return mixed
        */
        public function save(ShopInterface $shopList);

        /**
        * @param int $id
        *
        * @return mixed
        */
        public function getById(int $id);



        2) Implement interface in you repository and define functions



        <?php

        namespace VendorModuleModel;


        use VendorModuleApiDataShopInterface;
        use VendorModuleApiShopRepositoryInterface;
        use VendorModuleModelResourceModelShop as ShopResource;
        use MagentoFrameworkExceptionAlreadyExistsException;

        class ShopRepository implements ShopRepositoryInterface


        /**
        * @var ShopFactory
        */
        private $shopList;
        /**
        * @var Shop
        */
        private $shopListResource;

        public function __construct(
        ShopFactory $shopList,
        ShopResource $shopListResource
        )
        $this->shopList = $shopList;
        $this->shopListResource = $shopListResource;


        /**
        * @param ShopInterface $shop
        *
        * @return void
        *
        * @throws AlreadyExistsException
        * @throws Exception
        */
        public function save(ShopInterface $shop)

        try
        $this->shopListResource->save($shop);
        catch (AlreadyExistsException $e)
        //catch exception
        catch (Exception $e)
        //catch exception



        /**
        * @param int $shopId
        *
        * @return VendorModuleModelShop
        */
        public function getById(int $shopId)

        $shopListModel = $this->shopList->create();
        $this->shopListResource->load($shopListModel, $shopId);

        return $shopListModel;




        3) Add Repository and RepositoryInterface to di.xml



        <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
        <preference for="VendorModuleApiShopRepositoryInterface"
        type="VendorModuleModelShopRepository"/>
        </config>


        4) Start using it (i'm using it in controller)



         /**
        * @param ShopInterfaceFactory $shopListFactory
        * @param ShopRepositoryInterface $shopListRepository
        */
        public function __construct(
        VendorModuleApiDataShopInterfaceFactory $shopListFactory,
        VendorModuleApiShopRepositoryInterface $shopListRepository
        )
        $this->shopListFactory = $shopListFactory;
        $this->shopListRepository = $shopListRepository;


        public function execute()

        $shopId = 1;//use needed entity ID

        /**
        * Create entity
        *
        * @var Shop $shopList
        */
        $shopList = $this->shopListFactory->create();
        $shopList->setData(['name' => 'shop name']);
        $this->shopListRepository->save($shopList);

        /**
        * Read entity
        *
        * @var Shop $shopList
        */
        $shopList = $this->shopListRepository->getById($shopId);
        $shopData = $shopList->getData();//data of entity

        /**
        * Update entity
        *
        * @var Shop $shopList
        */
        $shopList = $this->shopListRepository->getById($shopId);
        $shopList->addData(['name' => 'bdn']);
        $this->shopListRepository->save($shopList);






        share|improve this answer















        Evgeniy Kapelko approach works, but deprecated from Magento 2.1(with certain version I might be mistaken).

        Below infromation from class, that was used in Evgeniy Kapelko approach, confirm info about deprecation vendor/magento/framework/Model/AbstractModel.php



        /**
        * Save object data
        *
        * @return $this
        * @throws Exception
        *
        * @deprecated 100.1.0 because entities must not be responsible for their own persistence.
        * Service contracts should persist entities. Use resource model "save" to implement
        * service contract persistence operations.
        */
        public function save()

        $this->_getResource()->save($this);
        return $this;




        How correct to work with you model?

        We need to use it like described in official documentation.



        It can be little bit hard at the begging, but future code will be simple and clear.



        In code below, we are going to update Shop entity name.

        1) Create interface for you repository, with functions getById and save



        <?php

        namespace VendorModuleApi;

        use VendorModuleApiDataShopInterface;

        /**
        * Interface SampleInterface
        *
        * @package AcademyDatabaseApiData
        */
        interface ShopRepositoryInterface


        /**
        * @param VendorModuleApiDataShopInterface $shopList
        *
        * @return mixed
        */
        public function save(ShopInterface $shopList);

        /**
        * @param int $id
        *
        * @return mixed
        */
        public function getById(int $id);



        2) Implement interface in you repository and define functions



        <?php

        namespace VendorModuleModel;


        use VendorModuleApiDataShopInterface;
        use VendorModuleApiShopRepositoryInterface;
        use VendorModuleModelResourceModelShop as ShopResource;
        use MagentoFrameworkExceptionAlreadyExistsException;

        class ShopRepository implements ShopRepositoryInterface


        /**
        * @var ShopFactory
        */
        private $shopList;
        /**
        * @var Shop
        */
        private $shopListResource;

        public function __construct(
        ShopFactory $shopList,
        ShopResource $shopListResource
        )
        $this->shopList = $shopList;
        $this->shopListResource = $shopListResource;


        /**
        * @param ShopInterface $shop
        *
        * @return void
        *
        * @throws AlreadyExistsException
        * @throws Exception
        */
        public function save(ShopInterface $shop)

        try
        $this->shopListResource->save($shop);
        catch (AlreadyExistsException $e)
        //catch exception
        catch (Exception $e)
        //catch exception



        /**
        * @param int $shopId
        *
        * @return VendorModuleModelShop
        */
        public function getById(int $shopId)

        $shopListModel = $this->shopList->create();
        $this->shopListResource->load($shopListModel, $shopId);

        return $shopListModel;




        3) Add Repository and RepositoryInterface to di.xml



        <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
        <preference for="VendorModuleApiShopRepositoryInterface"
        type="VendorModuleModelShopRepository"/>
        </config>


        4) Start using it (i'm using it in controller)



         /**
        * @param ShopInterfaceFactory $shopListFactory
        * @param ShopRepositoryInterface $shopListRepository
        */
        public function __construct(
        VendorModuleApiDataShopInterfaceFactory $shopListFactory,
        VendorModuleApiShopRepositoryInterface $shopListRepository
        )
        $this->shopListFactory = $shopListFactory;
        $this->shopListRepository = $shopListRepository;


        public function execute()

        $shopId = 1;//use needed entity ID

        /**
        * Create entity
        *
        * @var Shop $shopList
        */
        $shopList = $this->shopListFactory->create();
        $shopList->setData(['name' => 'shop name']);
        $this->shopListRepository->save($shopList);

        /**
        * Read entity
        *
        * @var Shop $shopList
        */
        $shopList = $this->shopListRepository->getById($shopId);
        $shopData = $shopList->getData();//data of entity

        /**
        * Update entity
        *
        * @var Shop $shopList
        */
        $shopList = $this->shopListRepository->getById($shopId);
        $shopList->addData(['name' => 'bdn']);
        $this->shopListRepository->save($shopList);







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited 2 days ago

























        answered Apr 4 at 12:10









        bdnbdn

        213




        213



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Magento Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f228465%2fupdate-a-field-in-database-via-model%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Bulk add to cart function issuecart vs. mini cart issue … rwd themeRedirect Add to cart button to cart pageAdd to cart issue - Magento 2.1The requested Payment Method is not available When creating an orderM2: reason add-to-cart might not function in production modeAdd to cart issue in some android devicesMagento 2 - custom price can not add to subtotal and grand total after add to cartAdd to cart codeIssue with my cart module on pdp and cart pages, just keeps spinningBulk price and quantity update using rest api

            БиармияSxpst500bh2ntaf! 3h2r