Laravel使用自定义Foregin键保存关系

时间:2018-07-11 09:15:00

标签: php laravel

在我的Web应用程序中,我必须表为schedule_instagram_accountsactions_logs

actions_logs的每一行都属于schedule_instagram_accounts外键的schedule_id表,

schedule_instagram_accounts

Schema::create('schedule_instagram_accounts', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('account_id')->unsigned();
    $table->foreign('account_id')->references('id')->on('instagram_accounts')->onDelete('cascade');
    $table->mediumText('todo');
    $table->timestamps();
});

actions_logs

public function up()
{
    Schema::create('actions_logs', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('schedule_id')->unsigned();
        $table->foreign('schedule_id')->references('id')->on('instagram_actions_histories')->onDelete('cascade');
        $table->tinyInteger('action_type')->index();
        $table->text('log');
        $table->timestamps();
    });
}

actions_logs模型:

class ActionsLog extends Model
{
    protected $guarded = ['id'];

    public function page(){
        return $this->belongsTo(ScheduleInstagramAccounts::class,'schedule_id');
    }
}

schedule_instagram_accounts模型:

class ScheduleInstagramAccounts extends Model
{
    protected $guarded = ['id'];
    protected $casts = [
        'todo' => 'array'
    ];

    public function page()
    {
        return $this->belongsTo(InstagramAccount::class);
    }

    public function log()
    {
        return $this->hasMany(ActionsLog::class, 'schedule_id');
    }
}

现在我想通过链接到actions_logs表的关系船将数据保存到schedule_instagram_accounts

ScheduleInstagramAccounts::find(1)->log()->create([
    'schedule_id' => 1, // is one row of schedule_instagram_accounts table
    'action_type' => 1,
    'log' => 'test'
]);

我收到此错误:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: 
a foreign key constraint fails 
(`instacheeta`.`actions_logs`, CONSTRAINT `actions_logs_schedule_id_foreign` 
FOREIGN KEY (`schedule_id`) 
REFERENCES `instagram_actions_histories` (`id`) ON DELETE CASCADE) 

(SQL: insert into `actions_logs` (`schedule_id`, `action_type`, `log`, `updated_at`, `created_at`) values (1, 1, eeeeeeeee, 2018-07-11 09:12:55, 2018-07-11 09:12:55))

更新:

但是此代码可以正常工作:

ActionsLog::create([
    'schedule_id' => '1',
    'action_type' => 1,  //like
    'log' => 'qqqqqqq'
]);

2 个答案:

答案 0 :(得分:1)

您在外键约束定义中犯了一个错误:

此行:

{
  "subject": "${subject}",
  "body": {
    "contentType": "HTML",
    "content": "${remarks}"
  },
  "start": {
    "dateTime": "${startTime}",
    "timeZone": "${timezone}"
  },
  "end": {
    "dateTime": "${endTime}",
    "timeZone": "${timezone}"
  },
  "location": {
    "displayName": "${spaceName}",
    "locationEmailAddress": "${spaceEmail}"
  },
  "attendees": [
    {
      "emailAddress": {
        "address": "${spaceEmail}",
        "name": "${spaceName}"
      },
      "type": "resource"
    }
  ]
}

应该是:

{
  "error": {
    "code": "ErrorItemNotFound",
    "message": "The specified object was not found in the store.",
    "innerError": {
      "request-id": "XXXXXXXXXXXXXXXX",
      "date": "2018-07-11T09:16:19"
    }
  }
}

Laravel还很聪明,可以为您填充外键,因此您必须这样做:

$table->foreign('schedule_id')->references('id')->on('instagram_actions_histories')->onDelete('cascade');

答案 1 :(得分:0)

您可以添加与schedule_instagram_accounts的关系,但是在表instagram_actions_histories表中的actions_logs外键中。我认为这是有问题的。试试这个:

new CronJob('* * * * * *', function() {

    if(Date.now().toString() === user.timestamp){

        let message = {
          // Relevant message stuff here
        };

        let transporter = nodemailer.createTransport({
            host: 'smtp.yoursmtpserver.com',
            port: 587,
            secure: false, // true for port 465, false for other ports
            auth: {
                user: account.user,
                pass: account.pass
            }
        });

        let mailOptions = {
            from: '"Fred Foo " <foo@example.com>', // sender address
            to: 'bar@example.com, baz@example.com', // list of receivers
            subject: 'Hello ✔', // Subject line
            text: message
            html: '<b>Hello world?</b>' // html body
        };

        transporter.sendMail(mailOptions, (error, info) => {
            if (error) {
                return console.log(error);
            }
            console.log('Message sent: %s', info.messageId);
        });
    });
});

或者这个:

#include <sstream> // defines std::basic_ostringstream

// ...

    // basic_ostringstream is movable but no copyable.
    // Make Format moveable.
    Format(Format&&) = default;

// ...

    // Cannot bind a reference to a temporary.
    // R-value reference is required here.
    friend Format operator<<(ostream& os, TempFormat&& f)