Jenssegers Laravel-Mongodb return null if get by parameter - mongodb

I'm new to Laravel-Mongodb, trying to get result by parameter but it's not working
Model:
use Jenssegers\Mongodb\Model as Eloquent;
class Customer extends Eloquent {
protected $connection = 'mongodb';
protected $collection = 'Customer';
}
Controller:
class AdminController extends Controller
{
public function index() {
return Customer::all();
}
public function show($id) {
return Customer::find($id);
}
}
It's alright for index() but it will return empty for show($id), it will work if using:
return Customer::find(1);
I'm not sure why it's not working with parameter, am I missing something?

You need to add one protected variable in your model like below
protected $primaryKey = “customerId”
You can add your own primary key to this variable but if you won’t add this line in model, model will by default take _id as your primary key and _id is autogenerated mongodb’s unique id.
Thats the reason why you are not able to get record by id.

1 is not a valid ObjectId. Try to find a valid ID with a tool like Robomongo or just list your customers with your index method to find out what the IDs are.
The query should look more like this:
return Customer::find("507f1f77bcf86cd799439011");
You can read more about MongoDBs ObjectId here:
https://docs.mongodb.org/manual/reference/object-id/

Related

Check if indexed field exists

I'm trying to migrate my application from hibernate search 5 to 6. What I noticed in version 6 is that a field validation is added and you can't search on fields that doesn't exists in the index. Unfortunately I have business logic that relied on that. Is there a way to access ElasticsearchIndexModel class(as far as I can see in this class is the fields state) and check if a specific field exists? Or is there any way to do that at all?
There is a metamodel API.
Something like this should work:
<T> boolean isSearchable(SearchMapping mapping, Class<T> entityClass,
String fieldPath) {
SearchIndexedEntity<T> entity = mapping.indexedEntity( entityClass );
IndexDescriptor index = bookEntity.indexManager().descriptor();
Optional<IndexFieldDescriptor> fieldOptional = index.field(fieldPath)
if (!fieldOptional.isPresent()) {
return false;
}
IndexFieldDescriptor field = fieldOptional.get();
return field.isValueField() && field.toValueField().type().searchable();
}
You can access the SearchMapping this way:
SearchMapping mapping = Search.mapping( entityManagerFactory );
Or:
SearchMapping mapping = Search.mapping( entityManager.getEntityManagerFactory() );
Or in Quarkus, you can simply have it injected into your beans:
public class MyBean {
#Inject
SearchMapping mapping;
...
}

Eloquient with relation not working with find

I am new to laravel. I am facing a very weird problem. I have a model comment which is related to User model in laravel.
The Relationships are defined as such
//App\User model
public function comments()
{
return $this->hasMany('App\comment');
}
And
//App\Comment model
public function User()
{
return $this->belongsTo('App\User');
}
now when i am fetching user and comment s using find and with it is returning data for all the users in the table. My code is like this: App\User::find(1)->with('comments')->get(); Can some one tell me what am doing wrong?
Try something like this
$comments=App\User::whereId(1)->comments->get();
This should load every comment associated with user with ID 1
//App\User model
public function comments() {
return $this->hasMany('App\comment','user_id','id');
}
//In your controller
use App\User;
$comment = User::where('id',2)->comments->get();
//I hope It's work for you!

laravel mongodb how to change _id to id on output?

I want to have _id in the database but want to output id when doing a query.
How can I achieve it?
You can try this (using an Accessor) :
Model
public function getIdAttribute() {
return $this->attributes['_id'];
}
Controller test
$user = User::find(1);
// this will call getIdAttribute which will return the `_id`
dd($user->id);
You can also override toArray() method if you want to show it :
Model
// ..
// getIdAttribute()
// ..
public function toArray()
{
$array = parent::toArray();
$array['id'] = $this->id;
unset($array['_id']);
return $array;
}
Controller Test
$user = User::find(1);
dd($user->toArray());
Another way to do this is using Transformers (http://fractal.thephpleague.com/transformers/). There is a service provider for Laravel here (https://github.com/gathercontent/laravel-fractal).
It will do that in a elegant way :)
Of course, if you need to do only with "id" field, I'll do like zorx told:
public function getIdAttribute() {
return $this->attributes['_id'];
}
But you'll probably put that in some BaseModel or abstractModel class, a parent for you models who need this.

How to make one to many relations for rest api call in yii2

I have creating rest api call.
I have two table
1. person - foreign key is id
2. contact - foreign key is personId
I have creating model for this one is
class Group extends ActiveRecord
{
public function relations()
{
return array(
'user'=>array(self::HAS_ONE,'User','id'),
'contact'=>array(self::HAS_MANY,'Contact','personId')
);
}
}
Controller is
public function actionView(){
$group=Group::find();
return $group;
}
Is this enough?. It is not working for me. How to make one to many relations in yii
ActiveModel::find() returns an ActiveQuery instance, it doesn't run the query.
You either use Group::findOne(primaryKey) or Group::findAll(condition) or do return $group->one(); or return $group->all();
As for the relations (in your model):
public function getUser()
{
return $this->hasOne(User::className(), ['id', 'user']);
}
public function getContact()
{
return $this->hasMany(Contact::className(), ['personId', 'user']);
}
You call the with $group->user and $group->contact. Make sure not to use the function directly, it also returns an ActiveQuery instance, which is not your actual object.

Laravel 5.0 hasManyThrough column not found issue

I am five days into Laravel and after hours of watching Jeffrey Way I decided to delve into building an app to learn.
I am stuck at the point of working with tables in a hasManyThrough layout and identifying the columns that are the linkage between the tables. Eloquent is trying to use a column called 'id" as primary key that it cannot find. In my tables I am using the naming convention tablename_id like below. In my class function, I nominate the columns to use, but it fails with the error:
QueryException in Connection.php line 620:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'cable_installations.id' in 'on clause' (SQL: select `cable_specifications`.*, `cable_installations`.`cable_specifications_id` from `cable_specifications` inner join `cable_installations` on `cable_installations`.`id` = `cable_specifications`.`cable_installations_id` where `cable_installations`.`cable_specifications_id` is null)
I am trying to retrieve:
A distinct list of cable specifications that are allowed with a selected cable_installation_method
Thanks!
TABLE 1: cable_specifications
cable_specifications_id (REPEATS)
other_columns...
TABLE 2: cable_installation_methods
cable_installation_methods_id (UNIQUE)
other_columns...
TABLE 3: cable_installations (PIVOT)
cable_specifications_id (REPEATS)
cable_installation_methods_id (REPEATS)
My classes are:
use Illuminate\Database\Eloquent\Model as Eloquent;
class CableInstallationMethod extends Eloquent {
protected $table = 'cable_installation_methods';
protected $fillable = [];
public function CableInstallation()
{
return $this->hasMany('CableInstallation');
}
public function CableSpecByInstall()
{
return $this->hasManyThrough('App\CableSpecification', 'App\CableInstallation', 'cable_specifications_id', 'cable_installations_id');
}
}
In my controller, I call this function per below:
public function VoltageDropLoad()
{
$InstallationMethods = CableInstallationMethod::all();
$CableSelected = CableInstallationMethod::where("cable_installation_methods_id", 1)->first();
$CableTypes = $CableSelected->CableSpecByInstall()distinct()->get()->toJson();
return view('pages.voltcalc', compact('InstallationMethods', 'CableTypes', 'CableTypes'));
}
Based on your CableInstallationMethod class, you may have missed defining the primary key field for your models:
use Illuminate\Database\Eloquent\Model as Eloquent;
class CableInstallationMethod extends Eloquent {
protected $table = 'cable_installation_methods';
/* Need to define $primaryKey column here, normally defaults to 'id' */
protected $primaryKey = 'cable_installation_methods_id';
protected $fillable = [];
public function CableInstallation()
{
return $this->hasMany('CableInstallation');
}
public function CableSpecByInstall()
{
return $this->hasManyThrough('App\CableSpecification', 'App\CableInstallation', 'cable_specifications_id', 'cable_installations_id');
}
}
With the primary key set you can also take advantage of using Model::find($id) instead of using Model:where(...)->first()
public function VoltageDropLoad()
{
$InstallationMethods = CableInstallationMethod::all();
$CableSelected = CableInstallationMethod::find(1);
$CableTypes = $CableSelected->CableSpecByInstall()->distinct()->get()->toJson();
return view('pages.voltcalc', compact('InstallationMethods', 'CableTypes', 'CableTypes'));
}