php - Laravel: method to set the value of a custom primary key

47

MyDocument model has a custom primary key name, so I typed:

class Document extends Model {

    protected $primaryKey = 'fluxo_mensagem_id';

After this, I suppose Laravel to know my primary key name and then I wouldn't expected to have to type it manually every time I need to set its value. Something like:

$document = new Document;
$document->setPrimary($pivot->id);

Instead of:

$document = new Document;
$document->fluxo_mensagem_id = $pivot->id;

For more details, my partial ER diagram:

enter image description here

Question 1

Laravel provides some method to set primary key values dynamically after custom names defined on model class?

Question 2

Ondocument table, the columnfluxo_mensagem_id is a foreign key that referencesidfluxo_mensagem pivot (intermediate) table. There's some way to "associate" (as we can do with Belongs To relationships)Pivot object to aDocument model?

For example:

  $pivot = $mensagem->fluxos()->first()->pivot;
  $document = new Document;
  $document->fluxoMensagem()->associate($pivot); 

This would fit the problem because his intention is to set the foreign key on the child model.

767

Answer

Solution:

Regarding Question 1: You can set the primary key value as any other, but you need to set the $incrementing = false, otherwise it'll be saved as 0.

/**
 * Indicates if the IDs are auto-incrementing.
 *
 * @var bool
 */
public $incrementing = false;

People are also looking for solutions to the problem: php - Cannot autowire service: Argument references class but no such service exists

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.