Ich versuche, einen Ansichtszähler für Produktansichten zu erstellen, also muss ich verfolgen, wie oft das Produkt geöffnet wird.Laravel - Eloquent Erstellen oder Aktualisieren von Modell
Also, was ich getan habe, ist eine neue Tabellen- erstellen
Schema::create('user_add_views', function (Blueprint $table)
{
$table->integer('user_id') ->unsigned() ->index();
$table->integer('add_id') ->unsigned() ->index();
$table->integer('total_view') ->integer() ->default(1);
//Removed all keys for making things faster
//Foreign Keys
$table->foreign('user_id') ->references('id') ->on('users');
$table->foreign('add_id') ->references('id') ->on('advertisements');
//Composite Primary Key
$table->unique([
'user_id',
'add_id'
],'user_add_views_ck');
});
Und ein neues modell-
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserAdvertisementView extends Model
{
protected $primaryKey = null;
public $incrementing = false;
public $timestamps = false;
protected $table = 'user_add_views'; //Table Name
protected $fillable = [
'user_id',
'add_id',
'total_view'
];
public function user()
{
return $this->hasOne('App\User','user_id');
}
public function advertisement()
{
return $this->hasOne('App\advertisement','add_id');
}
//Scope Query for view count
/**
* Scope a query for a mass Assignment
*
* @return \Illuminate\Database\Eloquent\Builder
*/
/*
public function scopeInsertData($query,$project_id,$data)
{
$bulk_data = array();
foreach ($data as $value)
{
array_push(
$bulk_data,
array(
'project_id' => $project_id,
'feature_id' => $value
)
);
}
return $query->insert($bulk_data);
}
*/
}
Und von Controller-
wie dieser AufrufUserAdvertisementView::firstOrCreate([
'user_id' => Auth::user()->id,
'add_id' => $requestData['product_id']
])->increment('total_view');
Aber es hat nicht funktioniert.
versuchte dann mit this-
$counter = UserAdvertisementView::firstOrNew([
'user_id' => Auth::user()->id,
'add_id' => $id
]);
if ($counter->exists)
{ // some way to check
$counter->total_view = $counter->total_view+1;
$counter->save();
return $counter;
}
else
{
$counter->save();
return "Created";
}
Wieder schlug fehl.
versucht dann mit-
$counter->increment('total_view',1);
Aber nichts funktioniert, und ich finde keine Antwort-wie this-
Kann jemand bitte helfen?
helfen kann Laravel auf das Speicherverzeichnis schreiben? Ich sehe oft keinen Fehler (d. H. "Diese Seite kann nicht erreicht werden"), wenn dies nicht möglich ist. –