Today I wanted to do some clean code so just started selecting columns for with relationship. With this code:
\App\Genre::with([
'family'
])->where([
'slug' => $slug,
'is_active' => true
])->first();
everything is working fine. But when I start selecting columns for "with" method:
\App\Genre::with([
'family' => function ($query) {
$query->select('name_pl', 'name_lat');
}])->where([
'slug' => $slug,
'is_active' => true
])->first();
I got that family is null (but it should be an object with columns: name_pl, name_lat). What I am doing wrong?
family method in Genre class looks like this:
public function family () {
return $this->belongsTo(Family::class);
}
I am using Laravel 5.4
Pretty sure you need to add a related column to the list of selected columns, otherwise Laravel won't b able to match the data to eager-load.
Assuming that Genre has a family_id and Family has an id primary key column specified, you need this:
$query->select('id', 'name_pl', 'name_lat'); // See the id added here?
Should do the trick.
For clarity, the matching I mentioned is this one:
select * from genre
select * from family where id in (1, 2, 3, 4, 5, ...)
-- where the comma-separated list of IDs consists of the unique family_id values retrieved in the first query.
Why don't you try:
\App\Genre::with('family:name_pl,name_lat')->where([
'slug' => $slug,
'is_active' => true
])->first();
Related
I have two tables with relationship one to one hasOne and have column same name
CRUD::addField([
'label' => "Title",
'type' => 'text',
'name' => 'new_title', // the db column for the foreign key
]);
CRUD::addField([
'label' => "Title",
'type' => 'text',
'name' => 'achive.new_title', // the db column for the foreign key
'entity' => 'achive',
]);
I just want show once but save both to two table
You need something that's call the callbacks method, the simplicity of that method is you can control what you want after create, edit, delete and etc.
So, in your controller just need one field name,
CRUD::addField([
'label' => "Title",
'type' => 'text',
'name' => 'new_title',
]);
After that, you can create a new trait in your controller for creating/updating your relationship,
use \Backpack\CRUD\app\Http\Controllers\Operations\CreateOperation { store as traitStore; }
And then, declare the store function,
public function store() {
// Get the value from the request
$request = $this->crud->getRequest();
// And then you can insert/update data into your relationship table
\DB::table('achives') // Your relation table
->updateOrInsert(
['new_title' => $request->new_title],
['other_column_name' => 'Value of your other column']
);
$response = $this->traitStore();
// do something after save
return $response;
}
The updateOrInsert method accepts two arguments: an array of conditions by which to find the record, and an array of column and value pairs indicating the columns to be updated. more info here
I user this code for insert data .
$conv = DB::table('conversations')
->insert([
'is_seen' => $other_user_id,
'user_one' => $user_id,
'user_two' => $other_user_id,
'user_one_status' => 1,
'user_two_status' => 0,
'message_status' => 0,
'last_message' => $messageCon
]);
Its return true false value. I need last inserted row.
Assuming there's a reason you're not using Eloquent, you could use insertGetId.
$conv = DB::table('conversations')
->insertGetId([
'is_seen' => $other_user_id,
'user_one' => $user_id,
'user_two' => $other_user_id,
'user_one_status' => 1,
'user_two_status' => 0,
'message_status' => 0,
'last_message' => $messageCon
]);
Caveats from the documentation:
Auto-Incrementing IDs
If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:
When using PostgreSQL the insertGetId method expects the auto-incrementing column to be named id. If you would like to retrieve the ID from a different "sequence", you may pass the column name as the second parameter to the insertGetId method.
Insert cant return whole row.
You can change it to insertGetId and then select it from database by that id.
Or use models, and use create method (Conversation::create([...]))
When a user first visits the page, the ListEntries table is ordered ascending by id and none of the ordering icons in the table header are active.
I would like to have the ListEntries table ordered by a column of my choosing, including having the icon next to this column active (either ascending or descending).
Is there a way to have the ListEntries table ordered by a column of my choosing when a user visits the page?
In your Controller's setup() method you can use:
$this->crud->orderBy('name', 'DESC');
Anything you pass to the orderBy() statement will be used on the Eloquent query.
By default, columns for real attributes (that have a correspondent column in the database) should be orderable. But you can also manually specify 'orderable' => true for columns, or define your own order logic. Note that relationship columns (1-n, n-n), model_function or model_function columns are NOT orderable by default, but you can make them orderable with orderLogic.
Hope it helps.
This can be done by manipulating the request object, which may be frowned upon in some circles.
This solution will also update the order icon on the appropriate column.
There are a number of ways to accomplish this, but one way would be to add the following to the setupListOperation() method of your Controller.
/** #var \Illuminate\Http\Request $request */
$request = $this->crud->getRequest();
if (!$request->has('order')) {
$request->merge(['order' => [
[
'column' => 'column-index-here',
'dir' => 'asc'
]
]]);
}
Use this key orderable it is a boolean
this->crud->addColumn([
'label' => 'Category',
'type' => 'select',
'name' => 'category_id', // the db column for the foreign key
'entity' => 'category', // the method that defines the relationship in your Model
'attribute' => 'name', // foreign key attribute that is shown to user
'orderable' => true,
'orderLogic' => function ($query, $column, $columnDirection) {
return $query->leftJoin('categories', 'categories.id', '=', 'articles.select')
->orderBy('categories.name', $columnDirection)->select('articles.*');
}
]);
Reference
Two tables 1 and 2, where id_schedule in 2 table is not primary key:
Task is to get the dates from table 2. I have the following code:
public function relations()
{
return array(
'scheduleTitles' => array(self::BELONGS_TO, 'ObjectScheduleTranslate', 'id'),
'scheduleDates' => array(self::BELONGS_TO, 'ObjectScheduleDate', array('id' => 'id_schedule'))
);
}
OK, first relation works well, second (for this task, exactly) returns only one record (this one 2013-12-30 00:00:00)which is first in screen.
Trying to use another approach, I coded the relation in first model:
'scheduleDates' => array(self::BELONGS_TO, 'ObjectScheduleDate', 'id')
at second model:
'scheduleDatesId' => array(self::HAS_MANY, 'ObjectSchedule', 'id_schedule')
which returns my empty set.
What am I doing wrong ?
Using Yii framework.
I have 3 models.
Articles - table articles(id, name)
ArticlesToAuthors - table articles_to_authors (id, article_id, author_id, type)
Authors - table authors (id, name)
I need to get authors.*, article_to_authors.type for specific article_id.
I was trying to make relation in ArticlesToAuthors model like that:
'authors' => array(self::HAS_MANY, 'Authors', array('id' => 'author_id'), ),
then i made query:
$authors = ArticlesToAuthors::model()->with('authors')->findAll(array('condition' => 'article_id=2217') );
foreach($authors as $a)
{
//this is not working
#var_dump($a->authors->name);
#var_dump($a->name);
//this works fine
foreach($a->authors as $aa)
{
var_dump($aa->name);
}
}
Can i get all active record object in one and not to do foreach in foreach?
I need an analogue to sql "SELECT atoa., a. FROM articles_to_authors atoa LEFT JOIN authors a ON atoa.author_id=a.id WHERE atoa.article_id=:article_id"
Am i doing right?
p.s. - sorry for my bad english.
It looks like you need the following relations:
in your ArticlesToAuthors table:
'author' => array(self::BELONGS_TO, 'Authors', 'author_id'),
'article' => array(self::BELONGS_TO, 'Articles', 'article_id'),
and, for completeness, in your Authors table:
'articlesToAuthors' => array(self::HAS_MANY, 'ArticlesToAuthors', array('id' => 'author_id'), ),
This should allow you to access $a->author->name. Not tested, that's just off the top of my head.