public function destroy(Request $request){
$customer = customer::find($request->ID);
$customer->delete();
}
Back Query
"delete from `customer` where `id` is null"
when using Laravel's eloquent, it returns back the query but why is id showing as null?
Change it to $request->id. So, do this:
public function destroy(Request $request){
Customer::destroy($request->id);
}
Or:
public function destroy(Request $request){
Customer::where('id', $request->id)->delete();
}
let's try this
it will work
customer::where('id', $request->ID)->delete();
You need to code like this.
public function destroy(Request $request){
Customer::where('id', $request->input('ID'))->delete();
}
fix the problem edit Primary key on model because on database is primary key is "ID" not "id"
protected $primaryKey = 'ID';
Related
this is my function
public function show($id)
{
$newproject = Newproject::find($id);
$data = [
'name' => $newproject->user->name
];
return $data;
}
newproject model
public function user()
{
return $this->hasOne(User::class,'user_id' ,'id');
}
it always getting the error
message: "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.user_id' in 'where clause' (SQL: select * from `users` where `users`.`user_id` = 1 and `users`.`user_id` is not null limit 1)"
exception: "Illuminate\Database\QueryException"
file: "C:\xampp\htdocs\larastart\vendor\laravel\framework\src\Illuminate\Database\Connection.php"
line: 669
please help my to solve my problem please.
Check the relationship one-to-one reference
The foreign_key user_id is in newprojects table, you need to build the relationship like this:
User model:
public function newproject()
{
return $this->hasOne(Newproject::class,'user_id');
}
newproject model:
public function user()
{
return $this->belongsTo(User::class);
}
I think it should be something like this,
public function user()
{
return $this->hasOne(User::class,'id' ,'user_id');
}
It means id of users table match with current model's user_id column. And if you have proper naming convention according to laravel then you don't need to pass this extra params.
Laravel hasOne relation
Hope it helps:)
found the problem in my model
in user model
public function newproject()
{
return $this->belongsTo(Newproject::class,'user_id','id');
}
in newproject model
public function user()
{
return $this->hasOne(User::class,'id' , 'user_id');
}
thanks all
I have a customer table which has a field called 'policy_id', where policy_id points to policy table. It is a null-able field, ie. Some customers may not have a policy.
I have a relationship code like this in Customer.php
public function policy() {
return $this->hasOne('App\Models\Policy', "id", "policy_id");
}
But when I issue a search request I am getting error like this:
Illuminate\Database\Eloquent\ModelNotFoundException: No query results for model [App\Models\Policy]
If I modify the function like this:
public function policy() {
if ($this->getAttribute('policy_id')) {
return $this->hasOne('App\Models\Policy', "id", "policy_id");
} else {
return null
}
}
But I am getting an error like this:
Call to a member function getRelationExistenceQuery() on null
Here is my search code:
$c = new Customer();
return Customer::doesntHave('policy')->orWhere(function (Builder $query) use ($req) {
$query->orWhereHas('policy', function (Builder $query) use ($req) {
$p = new Policy();
$query->where($req->only($p->getFillable()))
->orWhereBetween("policy_period_from", [$req->policy_period_start_from, $req->policy_period_start_to])
->orWhereBetween("policy_period_to", [$req->policy_period_end_from, $req->policy_period_end_to])
->orWhereBetween("payment_date", [$req->payment_date_from, $req->payment_date_to]);
});
})->where($req->only($c->getFillable()))->get();
Am I missing something or are there any other ways to do this?
PS: While debugging the above search code is returning successfully, but the exception happening from somewhere inside Laravel after the prepareResponse call.
Thanks in advance.
return $this->hasOne('App\ModelName', 'foreign_key', 'local_key');
Change the order, put the foreign_key policy_id in front of id
In your Customer Model, you need to use belongsTo method:
public function policy() {
return $this->belongsTo('App\Models\Policy', "policy_id", "id");
}
And In your Policy Model, use hasOne:
public function customer() {
return $this->hasOne('App\Models\Customer', "policy_id", "id");
}
First of all, you placed the wrong params.
$this->belongsTo('App\Models\Policy', "FK", "PK");
public function policy() {
return $this->belongsTo('App\Models\Policy','policy_id', 'id');
}
And for null value of policy_id you can use withDefault();
public function policy() {
return $this->belongsTo('App\Models\Policy','policy_id', 'id')->withDefault([
'name' => 'test'
]);;
}
there's a number of problems there but can you perhaps specify the namespace and the class of both your models - Customer and Policy.
By default, the models you create with php artisan make:model will use the \App namespace e.g. \App\Customer and \App\Policy.
Just double check that.
Also, with regards to the relationship, if the Laravel conventions have been followed you could just:
In the Customer model
public function policy() {
return $this->belongsTo(Policy::class);
}
In the Policy model
public function customer() {
return $this->hasOne(Customer::class);
}
of if a multiple customers can be under one policy
public function customers() {
return $this->hasMany(Customer::class);
}
Good luck
I got stuck in my code where I get wrong category in my article, for detail I will show my code,
Artikel model
class Artikel extends Model
{
protected $fillable = [
'judul', 'kutipan', 'slug', 'kategori_id','tag_id', 'isi', 'meta_keyword', 'meta_deskripsi', 'foto', 'status'
];
protected $table = 'artikel';
public function kategori(){
return $this->belongsTo('App\Kategori','id');
}
}
and this my Kategori model
protected $fillable = ['nama_kategori', 'slug'];
protected $table = 'kategori';
public function tag()
{
return $this->belongsTo('App\Tag','kategori_id');
}
public function artikel()
{
return $this->hasMany('App\Artikel','kategori_id');
}
and when I try this on php artisan tinker
Artikel::with('kategori')->where('slug','coba123')->get();
the result get wrong like this,
has anyone can help me? this make me confuse, I also have googling but still not change the result..
You are using the wrong column:
public function kategori(){
return $this->belongsTo('App\Kategori','kategori_id');
}
I have table query with field id which is autoincrement primary key.
Model
class Query extends \yii\db\ActiveRecord
{
public static function tableName()
{
return '{{%query}}';
}
public function rules()
{
return [
[['id', 'created_at'], 'integer'],
[['data'], 'string'],
];
}
}
Application
$q = new Query();
$q->created_at = time();
$q->data = Json::encode($query);
if ($q->save())
echo $q->id == null ? "null" : $q->id;
else
echo "Validation error";
Result is null, though new record with incremented id does occur in database.
Also I see only insert record in db log, but no record to obtain inserted row id.
What's wrong?
as you can see in vendor/yiisoft/yii2/db/ActiveRecord.php
there is already a primaryKey method
public static function primaryKey()
{
return static::getTableSchema()->primaryKey;
}
that return the proper primaryKey for the tableSchema
so you should not redefine this method ..
the method is specifically called primaryKey() not getPrimaryKey() .. this last one is the magic getter .. and return a value for var $primaryKey ..
if no insert is performed could be you have some validation problems .. try (just for debugging) using save(false)
I want to save the this following datetime while update or create so I wrote this in rules()
['createdon','default','value'=>date('Y-m-d H:i:s'),'on'=>'insert' ],
['updatedon','default','value'=>date('Y-m-d H:i:s'),'on'=>'update' ],
and I declare scenario in create and update functions as
public function actionCreate()
{
$model = new JobFunctionRole();
$model->scenario = 'insert';
....
....
}
public function actionUpdate($id)
{
$model = $this->findModel($id);
$model->scenario = 'update';
...
...
}
While create datetime stores perfectly.but in update its not stores.Whats the issue??Anybody?
You directly use _form
<?= $form->field($model, 'createdon')->hiddenInput('value'=>date("Y-m-d")])->label(false) ?>
These are validators for user input. You probably are looking for TimestampBehavior:
http://www.yiiframework.com/doc-2.0/yii-behaviors-timestampbehavior.html
The TimestampBehavior config should be added to an ActiveRecord model. Not the controller.