let data = require('./../../config/db')
let connection = data.connection
let sequelize = data.sequelize
let sql = function(){
let clubMembers = connection.define('club_members',{
position:{
type :sequelize.ENUM('President','Treasurer') ,
allowNull : false
}
},
{
classMethods : {
associate : function(models){
let clubMembers = models.club_members
let club = models.club
let student = models.student
club.hasMany(clubMembers,{
foreignKey : "club_id"
})
student.hasMany(clubMembers,{
foreignKey : "student_id"
})
}
}
}
);
return clubMembers;
}
module.exports = sql;
I dont need id attribute in this table but sequelize automatically creates it . And combination of both the foreign keys should be treated as primary key i.e composite primary key .
You should use belongsToMany in the associate function
associate: function(models){
models.club.belongsToMany(models.student, { through: models.club_members, foreignKey: 'club_id' });
models.student.belongsToMany(models.club, { through: models.club_members, foreignKey: 'student_id' });
}
This would create the club_members table with composite primary key consisting of club_id and student_id, without the default id column.
Related
I have a Controller class on which I execute a SOQL query to Custom Metadata Type records.
The SOQL query also contains a child relationship query (Master-Detail relationship).
I need to write a test with mock custom metadata records
#AuraEnabled(cacheable=true)
public static List<Response> getLeadMetadataValues() {
List<Lead_Business_Status__mdt> leadBusinessStatusList = [
SELECT Id, Label, DeveloperName, Index__c,
(SELECT Id, Label, DeveloperName, Reason_Status_Api_Name__c FROM Lead_Reason_Status__r)
FROM Lead_Business_Status__mdt ORDER BY Index__c ASC
];
List<Response> resList = new List<Response>();
if (Test.isRunningTest()) {
leadBusinessStatusList = new List<Lead_Business_Status__mdt>();
leadBusinessStatusList.add(createMock());
}
for (Lead_Business_Status__mdt bs : leadBusinessStatusList) {
Response res = new Response();
res.Id = bs.Id;
res.businessStatusLabel = bs.Label;
res.businessStatusDevName = bs.DeveloperName;
res.index = bs.Index__c;
for (Lead_Reason_Status__mdt rs : bs.Lead_Reason_Status__r) {
ReasonStatus rsObj = new ReasonStatus();
rsObj.Id = rs.Id;
rsObj.reasonStatusLabel = rs.Label;
rsObj.reasonStatusDevName = rs.DeveloperName;
rsObj.fieldApiName = rs.Reason_Status_Api_Name__c;
res.reasonStatusList.add(rsObj);
}
resList.add(res);
}
return resList;
}
I use Test.isRunningTest() to populate the leadBusinessStatusList with the mock data.
I am able to create a mock object for the Master record: Lead_Business_Status__mdt and Detail record: Lead_Reason_Status__mdt. However, I wasn't able to add the Detail record to the related list: Lead_Reason_Status__r
private static Lead_Business_Status__mdt createMock() {
String reasonStatusStr = '{"Label":"Transfer to Queue", "DeveloperName":"Transfer_to_Queue", "Reason_Status_Api_Name__c":"Transfer_to_Queue"}';
Lead_Reason_Status__mdt reasonStatusObj = (Lead_Reason_Status__mdt) System.JSON.deserialize(reasonStatusStr, Lead_Reason_Status__mdt.class);
System.debug('Lead_Reason_Status__mdt: ' + reasonStatusObj);
String businessStatusStr = '{"Label":"Wrong Lead", "DeveloperName":"Wrong_Lead", "Index__c":"1"}';
Lead_Business_Status__mdt businessStatusObj = (Lead_Business_Status__mdt) System.JSON.deserialize(businessStatusStr, Lead_Business_Status__mdt.class);
return businessStatusObj;
}
The test is covered except the inner for loop of the Lead_Reason_Status__mdt.
How can I create a mock object with populating the child relationship list?
Can you try use JSON.deserialize method to setup these metadata records.
List<Lead_Business_Status__mdt> leadBusinessStatusList = (List< Lead_Business_Status__mdt >) JSON.deserialize( '[{"Id": "xoid914011599", "Label": "test", "DeveloperName": "test","Reason_Status_Api_Name__c": "test"}, {"Id": "xoid9140115992","Label":"test2","DeveloperName": "test2","Reason_Status_Api_Name__c": "test2"}]', List<Lead_Business_Status__mdt>.class );
I migrated my database from Sql Server to MongoDB
I want to Join existing customer Table with contact Table .
Customer have multiple contacts . I tried whereRaw lookup
customer collection
{
"_id": 77,
"custid": 93
}
Contact Collection
{"_id":77,"contactid":77,"custid":93,"firstname":"Christy ","lastname":"Lambright" }
{"_id":79,"contactid":79, "custid":93,"firstname":"Marlys ","lastname":"Barry" }
Customer Modal
class custt extends Model
{
use Notifiable;
protected $primaryKey = 'id';
}
Contact Modal
class contact extends Model
{
use Notifiable;
protected $primaryKey = 'id';
In Controller
$cnt = DB::collection("custts")->raw(function($collection)
{
$more_where = [];
$more_where[]['$lookup'] = array(
'from' => 'contacts',
'localField' => 'custid',
'foreignField' => 'custid',
'as' => 'country',
);
return $collection->aggregate($more_where);
});
Error comes --
Empty Results
I tried Lots of options for hasMany and belongstoMany . Not working ...
please suggest
ok , finally found it working
source - https://github.com/jenssegers/laravel-mongodb/issues/841
$cnt = custt::raw(function($collection)
{
return $collection->aggregate(
[[
'$lookup' => [
'as'=>'info',
'from'=>'contacts',
'foreignField'=>'custid',
'localField'=>'custid'
]
]]
);
});
I have two models TeamMember and ProjectRequest.
A TeamMember can have one ProjectRequest, that is why I created the following Eloquent relationship on TeamMember:
class TeamMember extends Model {
//
protected $table = 'team_members';
protected $fillable = ['project_request_id'];
// Relations
public function projectTeam() {
return $this->hasOne('\App\Models\ProjectRequest', 'project_request_id');
}
}
In my Controller I want to query both tables, however it returns the failure message.
What is important to know is that $request->projectTeam is an array of emails, looking like this:
array:2 [
0 => "mv#something.com"
1 => "as#something.com"
]
Meaning that I need to bulk insert into team_members table the project_request_ id for each team member where the emails are in the array.
How can I do that in the right way? The following is my attempt:
public function createProjectTeam(Request $request){
try {
$title = $request->projectTitle;
$TeamMember = $request->projectTeam;
$projectRequest = ProjectRequest::create(['project_title' => $title]);
$projectRequestId = $projectRequest->id;
$projectTeam = $this->teamMembers->projectTeam()->create(['project_request_id'=> $projectRequestId])->where('email', $TeamMember);
//$projectTeam = TeamMember::createMany(['project_request_id' => $projectRequestId])->where($TeamMember);
//dd($projectTeam);
return $projectRequest.$projectTeam;
} catch(\Exception $e){
return ['success' => false, 'message' => 'project team creation failed'];
}
}
There are a few things you can do.
Eloquent offers a whereIn() method which allows you to query where a field equals one or more in a specified array.
Secondly, you can use the update() method to update all qualifying team members with the project_request_id:
public function createProjectTeam(Request $request)
{
try {
$projectRequest = ProjectRequest::create(['project_title' => $request->projectTitle]);
TeamMember::whereIn('email', $request->projectTeam)
->update([
'project_request_id' => $projectRequest->id
]);
return [
'success' => true,
'team_members' => $request->projectTeam
];
} catch(\Exception $e) {
return [
'success' => false,
'message' => 'project team creation failed'
];
}
}
I hope this helps.
I need to update the database table according to the edited data.
controller
public function update(Request $request)
{
$subscriptionplan = SubscriptionPlan::find($request->id);
$subscriptionplan->update($request->all());
return back();
}
But nothing happens when I submit the form. When I use dd($request->all()); at the beginning of the function, it correctly shows the edited data as follows.
array:10 [▼
"_method" => "patch"
"_token" => "gOCL4dK6TfIgs75wV87RdHpFZkD7rBpaJBxJbLHF"
"editname" => "SUP_EVA_001"
"editdesc" => "des"
"editprice" => "1000.050"
"editlimit" => "1"
"editperunit" => "20.000"
"editexceedunit" => "30.000"
"productid" => "1"
"id" => "1"
]
But database has not been updated.
My table name is Table: subscription_plans and model is SubscriptionPlan
These are the table columns:
protected $fillable = [
'name',
'description',
'price',
'usage_limit',
'charge_per_unit',
'charge_per_unit_exceed',
'is_limit_exceed_considered',
'product_id'
];
Any idea on how to solve it or what I have done wrong?
If your solution did not work, try the 1by1 like this.
public function update(Request $request)
{
$subscriptionplan = SubscriptionPlan::find($request->id);
$subscriptionplan->_method = $request->_method;
$subscriptionplan->_token = $request->_token;
$subscriptionplan->editname = $request->editname;
$subscriptionplan->editdesc = $request->editdesc;
$subscriptionplan->editprice = $request->editprice;
$subscriptionplan->editlimit = $request->editlimit;
$subscriptionplan->editperunit = $request->editperunit;
$subscriptionplan->editexceedunit = $request->editexceedunit;
$subscriptionplan->productid = $request->productid;
$subscriptionplan->save();
return back();
}
In order for Laravel to automatically fill the model attributes, the indexes of the array passed to the fill method must correspond to your model attributes names.
Also, instead of
$subscriptionplan->update($request->all());
Use
$subscriptionplan->fill($request->all());
Then save the subscription plan with $subscriptionplan->save();
I don't use 'id' column in DB.
Instead, I use a composite primary key user_id + tmdb_id.
If I add new record like this:
$movie = new Movie();
$movie->user_id = 1;
$movie->tmdb_id = 2;
$movie->ratio = 3;
$movie->save();
it works fine!
But if I try to edit an existing record like this:
$movie = Movie::where([
'user_id' => 1,
'tmdb_id' => 2,
])->first();
$movie->ratio = 4;
$movie->save();
Then I have the error:
Unknown column 'id' in 'where clause'.
The migration file looks like this:
public function up()
{
Schema::create('movies', function (Blueprint $table) {
$table->integer('user_id')->unsigned();
$table->integer('tmdb_id')->unsigned();
$table->tinyInteger('ratio');
// composite primary key
$table->primary(['user_id', 'tmdb_id']);
});
}
Laravel doesn't support composite primary keys.
You have to use an additional package like https://github.com/mpociot/laravel-composite-key.