How can I send a value from Controller to Model and how to receive the value in the Model.
I let above a picture of my database tables.
enter image description here
Example: If I enter in the input 3 action movies
$category=category::with('film')->where('name','=','Action')->first();
Film model:3
class film extends Model{
protected $table = "film"; //Para nao dar o erro de singular e plural
protected $primaryKey = 'film_id';
public $timestamps = false;
use HasFactory;
protected $sql=['film_id', 'title', 'release_year'];
public function category(){
return $this->belongsToMany(category::class,'film_category', 'film_id', 'category_id');
}
}
Category model:
class category extends Model{
protected $table = "category";
protected $primaryKey = 'category_id';
public $timestamps = false;
use HasFactory;
protected $sql=['category_id','name'];
public function film(){
return $this->belongsToMany(film::class,'film_category', 'category_id', 'film_id');
}
}
NOTE: I realized that I need to add in the front of the Category model
->take(3)
But I don't know how to send the value(3 or other else) via $category query.
You can simply put conditions in the closure of the "film" relationship on the controller to get 3 action movies or any number of movies.
Controller:
$limit = 3;
$category=category::with(['film'=>function($query)use($limit)
{
$query->limit($limt);
}])->where('name','=','Action')->first();
Controller Side
$category=category::with('film')->where('name','=','Action')->film->category($value);
Model Side
public function category($value){
return $this->belongsToMany(category::class,'film_category', 'film_id', 'category_id')->where('foo', $value);
}
Related
I'm new to laravel and I'm making a small api with just two tables to start. I have roles and people. I want to assign a role to a person from the store method but I don't understand how associate() works or how to implement it in the store method, this is what i have;
Model Rol:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
use HasFactory;
protected $fillable = ['id', 'rol'];
public function personas()
{
return $this->hasMany(Persona::class);
}
}
Model Persona:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Role;
class Persona extends Model
{
use HasFactory;
protected $fillable = ['id', 'nombres', 'apellidos', 'rol_id'];
public function rol()
{
return $this->belongsTo(Role::class, 'rol_id');
}
}
$rol = Role::find(1);
$persona->rol()->associate($rol);
$persona->save();
Persona controller store method:
public function index()
{
return PersonaResource::collection(Persona::with('rol')->paginate(25));
}
public function store(Request $request)
{
//$rol = Role::find(1);
$persona = new Persona();
// datos que voy a guardar
$persona->nombres = $request->nombres;
$persona->apellidos = $request->apellidos;
$rol = new Role();
//$rol->personas()->save($rol);
$persona->rol()->save($rol);
}
I want to know how to correctly associate both models to be able to correctly save the related data
I can't get the value of the foreign key that is inside the booking table.
Booking Table
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class booking extends Model
{
protected $primaryKey = 'bookingID';
protected $fillable = ['clientID', 'checkInDate', 'checkOutDate', 'roomsCount', 'roomTypeID', 'adultsCount', 'childrenCount', 'amenityID', 'paymentID'];
public function client()
{
return $this->hasOne(Client::class,'clientID');
}
}
Client Table
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class client extends Model
{
protected $primaryKey = 'clientID';
protected $fillable = ['fullNmae', 'firstName', 'lastName', 'phoneNumber', 'emailAddress'];
public function booking()
{
return $this->hasMany(Booking::class);
}
}
I tried adding the protected $primaryKey = 'bookingID'; and protected $primaryKey = 'clientID'; as suggested in my previous question but now I still can't get just the FirstName from the client table.
$bookingDetail = booking::with('client')->get();
return $bookingDetail->client->firstName;
You are trying to get a property from a collection in these lines:
$bookingDetail = booking::with('client')->get();
return $bookingDetail->client->firstName;
but this property client is defined for object, not a collection. so to solve it you must take one object from the collection like the following:
$bookingDetail = booking::with('client')->first();
return $bookingDetail->client->firstName;
i thing you need to try this one:
in your booking model:
// 'App\Client' these is example you need to put your client model path
public function client()
{
return $this->belongsTo('App\Client','clientID');
}
in your client model:
public function booking()
{
return $this->hasMany('App\Booking' , 'clientID');
}
I'm a beginner in cakePHP and I'm kind of stuck about retrieving data.
I have a controller, in which I want to get a users deposit amount.
Therefore I have a user model and a deposit model.
The deposit model looks like this:
<?php
App::uses('AppModel', 'Model');
class Deposit extends AppModel {
public $belongsTo = array('User');
public $useTable = 'deposits';
public $validate = array();
public function __construct($id = false, $table = null, $ds = null) {
parent::__construct($id, $table, $ds);
}
public function getDepositAmount() {
// return a users deposit amount
}
}
?>
How can I tell the model to return the amount (database field is called deposit_amount) and how does it know to which user id it belongs to? Thank you!
Uses of belongsTo in CakePhp
class Deposit extends AppModel {
public $useTable = 'deposits';
public $validate = array();
public function __construct($id = false, $table = null, $ds = null) {
parent::__construct($id, $table, $ds);
}
public function getDepositAmount() {
$this->belongsTo('User')
->setForeignKey('user_id');
// your find query here
}
}
Please read doc first for better understanding CakePhp Doc
I'm effectively trying to define the relationships between users (sender and recipient) and messages.
My Messages migration is:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMessagesTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
//
Schema::create('messages', function($t){
$t->increments('id');
$t->integer('sender_user_id')->unsigned();
$t->integer('recipient_user_id')->unsigned();
$t->string('subject');
$t->text('content');
$t->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
//
Schema::dropIfExists('messages');
}
}
My Message model was straightforward:
<?php
class Message extends Eloquent{
// link to sender user id
public function from(){
return $this->hasOne('User', 'sender_user_id');
}
// link to recipient user id
public function to(){
return $this->hasOne('User', 'recipient_user_id');
}
}
But I'm unsure in defining the hasMany relationships in my User model.
The docs (http://laravel.com/docs/eloquent#relationships) shows the following:
return $this->hasMany('Comment', 'foreign_key');
return $this->hasMany('Comment', 'foreign_key', 'local_key');
Now, I'm confused which key is which in the latter hasMany relationship. Which is correct for my User model?
public function sentMessages(){
return $this->hasMany('Messages', 'id', 'sender_user_id');
}
public function sentMessages(){
return $this->hasMany('Messages', 'sender_user_id', 'id');
}
You have to set your relation like this:
public function sentMessages()
{
return $this->hasMany('Messages', 'sender_user_id');
}
public function receivedMessages()
{
return $this->hasMany('Messages', 'recipient_user_id');
}
can any one tell me how to create a model object inside a constructor in yii. I had written the code as belo
<?php
class DistributorsController extends Controller
{
public $layout = '//layouts/column4';
public $defaultAction = null;
public function __construct()
{
echo '<br>Into constructor';
parent::__construct('Distributors','distributors');
}
public function actionDistributors()
{
$this->render("ChannelMask");
}
}
?>
But it is displaying only "Into constructor" string and view is not showing in my browser.
You need to call a model into the Controller.
Create a model, then in Controller, call it like :
Distributor::model()->findAll($criteria); //many models
or
Distributor::model()->findById($id); // one model
Like any other place if you want to create a new model:
$model = new Distributors();
or
$model = $this->loadModel($id, 'Distributors');
if you want to populate your model with existing data, then:
$model = Distributor::model()->findAll(); // all there is
or
$model = Distributor::model()->findByPk($id); // find by primary key