I'm trying to upgrade my existing Laravel 4 project to version 5.
Model relationships are not working fine. Every time I try to access a property from property_price table it returns null.
My models are located in App/Models directory.
Property Model
class Property extends \Eloquent {
protected $guarded = array('id');
protected $table = 'properties';
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $softDelete = true;
public function propertyPrice()
{
return $this->hasOne('PropertyPrice','pid');
}
}
PropertyPrice Model
class PropertyPrice extends \Eloquent {
protected $guarded = array('id');
protected $table = 'property_pricing';
public function property()
{
return $this->belongsTo('Property');
}
}
Usage
$property = Property::find($id);
$price = $property->property_price->per_night_price; // null
The code is working fine in Laravel 4.
You need to specify namespace in relation methods.
If you're using php5.5+ then use ::class constant, otherwise string literal:
// App\Models\PropertyClass
public function property()
{
return $this->belongsTo(Property::class);
// return $this->belongsTo('App\Models\Property');
}
// App\Models\Property model
public function propertyPrice()
{
return $this->hasOne(PropertyPrice::class,'pid');
// return $this->hasOne('App\Models\PropertyPrice','pid');
}
Of course you need to namespace the models accordingly:
// PSR-4 autoloading
app/Models/Property.php -> namespace App\Models; class Property
Related
I have i like query in my model but it doesn't work
Model:
<?php namespace App\Models;
use CodeIgniter\Model;
class SearchModel extends Model
{
protected $table = 'sport_tbl';
protected $primaryKey = 'id';
protected $returnType = 'array';
public function search($word)
{
$this->db->like('title', $word);
$res = $this->db->get('sport_tbl')->result_array();
return $res;
}
}
Controller:
<?php namespace App\Controllers\api;
use App\Controllers\BaseController;
use App\Models\SearchModel;
class Search extends BaseController
{
public function index()
{
$searchModel = new SearchModel();
$data['allnews'] = $searchModel->search('test');
return view('welcome_message', $data);
}
}
And this is error:
Call to undefined method CodeIgniter\Database\MySQLi\Connection::like()
You are basically using the old query builder style from Codeigniter 3 instead of Codeigniter 4.
In Codeigniter 4 your code should look like this.
<?php namespace App\Models;
use CodeIgniter\Model;
class SearchModel extends Model
{
protected $table = 'sport_tbl';
protected $primaryKey = 'id';
protected $returnType = 'array';
public function search($word)
{
$db = \Config\Database::connect();
$builder = $db->table('sport_tbl');
$builder->like('title', $word);
return $builder->get()->getResultArray();
}
}
In this case your controller should be just the same.
However there's another way of doing the same without creating a new database object and using the same one that is being automatically created for you.
<?php namespace App\Models;
use CodeIgniter\Model;
class SearchModel extends Model
{
protected $table = 'sport_tbl';
protected $primaryKey = 'id';
protected $returnType = 'array';
public function search($word)
{
$this->like('title', $word);
return $builder->get()->getResultArray();
}
}
In this case your controller should be a bit different:
<?php namespace App\Controllers\api;
use App\Controllers\BaseController;
use App\Models\SearchModel;
class Search extends BaseController
{
public function index()
{
$searchModel = new SearchModel();
$data['allnews'] = $searchModel->search('test')->getAll();
return view('welcome_message', $data);
}
}
The second version of the code is actually better because that way your can have as many functions you want in your model and then just call them in a chain statement always returning $this.
namespace App;
use App\Model\Service\Area;
use App\Model\Bid\Service;
use Illuminate\Database\Eloquent\Model;
class Bid extends Model
{
protected $table = "bid";
protected $primaryKey = 'bid_id';
protected $guarded = [];
protected $with = ['services'];
public function services() {
return $this->hasMany(Service::class, 'bid_id');
}
public function area() {
return $this->belongsTo(Area::class, 'area_id', 'area_id');
}
}
namespace App\Model\Service;
use Illuminate\Database\Eloquent\Model;
class Area extends Model
{
protected $table = "location_area";
protected $primaryKey = 'area_id';
protected $guarded = [];
public function city()
{
return $this->belongsTo(City::class, 'city_id');
}
}
Area table Migration and data
Bid table Migration and data
When I am trying to access
Bid::with('area')->find(BID_ID);
It is returning Null
Query is firing wrong:
"select * from `location_area` where `location_area`.`area_id` in (0)"
But if I am doing like:
$bid = Bid::find(BID_ID);
dd($bid->area);
It returns Area table values. What is going wrong? Please Help me. I
am having this problem for a long time. Thank You in advance :)
you must be declared a method in your MID model
public function area()
{
return $this->belongsTo(Area::class, 'bid');
}
something like this
after this, you access area in with()
Bid::with('area')->find(BID_ID);
Change this function in your Bid model :
public function area() {
return $this->belongsTo(Area::class, 'area_id');
}
I'm try to create a relationship between albums and photos (an Album has many photos). Below is my controller and what my models look like. Interesting enough, the reverse relationship photo->album (belongsTo) works fine! but the album->photos returns an empty collection.
## The hasMany relationship does NOT work... I get an empty collection
<?php
class AlbumController extends BaseController
{
public function show(Request $request, $album_id)
{
$album = Album::find($album_id);
dd($album->photos);
}
}
## Results:
# Collection {#418
# items: []
# }
## The belgonsTo relationship works
<?php
class PhotoController extends BaseController
{
public function show(Request $request, $photo_id)
{
$photo = Photo::find($photo_id);
dd($photo->album);
}
}
<?php
namespace App;
use DB;
use Jenssegers\Mongodb\Eloquent\SoftDeletes;
use Moloquent;
class Album extends Moloquent
{
use RecordActivity, SoftDeletes;
protected $connection = 'mongodb';
protected $table = 'albums';
protected $collection = 'albums';
protected $primaryKey = "_id";
protected $dates = ['deleted_at'];
protected $fillable = ['user_id','name','is_private'];
public function photos()
{
// Neither seems to work
//return $this->embedsMany('Photo');
return $this->hasMany('App\Photo');
}
}
<?php
namespace App;
use DB;
use Jenssegers\Mongodb\Eloquent\SoftDeletes;
use Moloquent;
class Photo extends Moloquent
{
use RecordActivity, SoftDeletes;
protected $connection = 'mongodb';
protected $table = 'photos';
protected $collection = 'photos';
protected $primaryKey = "_id";
protected $dates = ['deleted_at'];
protected $fillable = ['album_id', 'user_id', 'name', 'folder', 'is_private', 'caption'];
protected $hidden = [];
// user and album belongsTo works
public function user()
{
return $this->belongsTo('App\User');
}
public function album()
{
return $this->belongsTo('App\Album');
}
}
The issue had to do with the fact that my IDs were ObjectID and it seems to be an issue with Jessengers Laravel MongoDB Drivers... we have actually decided to move back to MariaDB to fully utilize Eloquent/Relationships
I did the same thing as yours and i found that nothing wrong with Mongodb. Because Mongodb defined the "_id" as primary key and that's the reason it couldn't get the correct relationship: belongsTo and hasMany. So i did a small change by declared the $primaryKey = "id" on the top of parent Model and it worked fine
this worked for me.
/**
* #return HasMany
*/
public function tasks(): HasMany
{
return $this->hasMany(ProjectTask::class, 'project_id', 'idAsString');
}
I am trying to abstract my models using a single base class. I have three models that inherit from the same base:
Repair
Inspection
Purchase
I am able to successfully create and persist the models to the DB, but when fetching I get a blank screen, no errors are thrown. When I remove the $with attribute everything seems to work.
Heres the code:
abstract class ItemType extends Model
{
public $timestamps = false;
protected $with = ['details'];
public function details()
{
return $this->morphOne(Item::class, 'type', 'item_details_type', 'item_details_id', 'id');
}
}
class Repair extends ItemType
{
protected $table = 'repairs';
protected $guarded = ['id', 'created_at', 'updated_at'];
protected $morphClass = self::class;
}
class Inspection extends ItemType {}
class Purchase extends ItemType {}
In the end I decided to use morphTo relationships without the abstract class to solve the issue.
I have four tables and I am giving my table structure here
user_work['id', 'user_id', 'work_id']
work_sectors['id', 'name', 'status']
works['id', 'work_sector_id', 'work_type_id', 'work_duration_id', 'name']
users['id', ...]
And My Models are
class User extends Eloquent implements UserInterface, RemindableInterface
{
use UserTrait, RemindableTrait;
protected $table = 'users';
public function work()
{
return $this->belongsToMany('Work', 'user_work');
}
}
class Work extends \Eloquent {
protected $fillable = [];
protected $table_name = 'works';
public $timestamps = false;
public function user()
{
return $this->belongsToMany('User', 'user_work');
}
public function sector()
{
return $this->belongsTo('WorkSector', 'work_sector_id');
}
}
In my controller I have written this code
$user = User::with('language')->with('work')->find($userId);
Here I need name of work_sector table but probably I have written wrong code to get the sector name.
So please help me to write a proper function in this eloquent method in laravel 4.2.